如何使用PowerShell比较文本文件和csv文件



我有一个txt文件调用EmployeeID.txt看起来像这样

Number      ID
32324       KLEON
23424       MKEOK

我有一个CSV文件名为fullinventory。CSV看起来像这样

Name     URL        UPN               Status
John    http://     KLEON@COM.COM     Yes

我试图比较两个文件和输出2个不同的文件名为matchFound.csnotFound.txt文件。

如果ID在FullInventory.csv中找到EmployeeID.txt,然后输出matchFound.csv从FullInventory.csv

如果ID如果在FullInventory.csv中找不到EmployeeID.txt,则输出NotFound.txt数据来自EmployeeId.txt

$ImportTXT = Import-CSV -path $Global:EmployeeID -Delimiter "`t"
$ImportFullInv = Import-CSV -Path $Global:FullInventory 

ForEach ($TxtLine in $ImportTXT) {
$TxtID = $TxtLine.ID
if ($null -eq $txtID -or $txtID -eq '') {
Write-Host "ID is empty"
}
else {
$array = @();
ForEach ($CSVLine in $ImportFullInv) {
$CSVUPN = $CSVLine.UPN
$UPNSPLIT = $CSVUPN -split "@"
$array += $UPNSPLIT[0]
}
if ($array -contains $TxtID) {
// Something is not right here.

$CSVLine |  Export-Csv -Path "C:UsersDesktopmatchFound.csv" -append


}
else {
$TxtLine | Out-File -FilePath  "C:UsersDesktopnotFound.txt" -append
}
}
}

我现在的问题是matchFound.csv文件没有输出正确的数据。我想它输出的是csv文件中最后的数据列而不是匹配的。如有任何帮助或建议,我将不胜感激。

这可以使用Group-Object -AsHashtable来实现快速查找,散列键将是从UPN列中提取的Name。除了将其导出到两个不同的文件之外,还可以使用可步进的管道而不是使用-Append

$map = Import-Csv $FullInventory -Delimiter "`t" |
Group-Object { [mailaddress]::new($_.UPN).User } -AsHashTable -AsString
$pipeMatch = { Export-Csv 'C:UsersDesktopmatchFound.csv' -NoTypeInformation }.GetSteppablePipeline()
$pipeMatch.Begin($true)
Import-Csv $EmployeeID -Delimiter "`t" | ForEach-Object {
# if this ID exists in the full inventory
if($map.ContainsKey($_.ID)) {
# export all rows from inventory matching this ID
$map[$_.ID] | ForEach-Object { $pipeMatch.Process($_) }
# and go to the next ID
return
}
# else, export this line to the not found csv
$_
} | Export-Csv "C:UsersDesktopnotFound.csv" -NoTypeInformation
$pipeMatch.End()

最新更新