这可能太复杂了,但在这里你去:
假设这是您的 CSV 文件:
"Name","OS","Type"
"htew804","Windows","WindowsAutherServer"
"wddg9028","Windows","WindowsAutherServer"
"other321","Windows","WindowsBackupServer"
这是您的文本文件的内容:
wddg9028
test1234
htew804
然后这段代码:
$csvFile = 'D:\blah.csv'
$txtFile = 'D:\names.txt'
# import the .csv file
$csv = Import-Csv -Path $csvFile
# read the .txt file which contains only server names, each on a separate line
$txt = Get-Content -Path $txtFile
$items = Compare-Object -ReferenceObject $txt -DifferenceObject $csv.Name -IncludeEqual -PassThru
$result = foreach ($item in $items) {
$name = $item.ToString()
switch ($item.SideIndicator) {
'<=' {
# the servername is only present in the text file
[PSCustomObject]@{
Name = $name
OS = ''
Type = ''
SideIndicator = $item.SideIndicator
Comment = "Name only found in $txtFile"
}
break
}
default {
# '==' AND '=>': the servername is only present in the csv file or in both files
$server = @($csv | Where-Object { $_.Name -eq $name })[0]
[PSCustomObject]@{
Name = $server.Name
OS = $server.OS
Type = $server.Type
SideIndicator = $item.SideIndicator
Comment = if ($item.SideIndicator -eq '==') { "Name found in both files" } else { "Name only found in $csvFile" }
}
}
}
}
$result | Format-Table -AutoSize
产生这个结果:
Name OS Type SideIndicator Comment
---- -- ---- ------------- -------
wddg9028 Windows WindowsAutherServer == Name found in both files
htew804 Windows WindowsAutherServer == Name found in both files
other321 Windows WindowsBackupServer => Name only found in D:\blah.csv
test1234 <= Name only found in D:\names.txt
如果您希望将此信息写入新的 CSV 文件,Format-Table -AutoSize
请将Export-Csv -Path 'D:\blah_updated.csv' -NoTypeInformation