我有一个 txt 文件调用 EmployeeID.txt 看起来像这样
Number ID
32324 KLEON
23424 MKEOK
我有一个名为 FullInventory.csv 的 CSV 文件,看起来像这样
Name URL UPN Status
John http:// [email protected] Yes
我正在尝试比较这两个文件并输出 2 个不同的文件,分别称为 matchFound.csv 和 notFound.txt 文件。
如果在 FullInventory.csv 中找到来自 EmployeeID.txt 的 ID,则使用 FullInventory.csv 中的所有列输出 matchFound.csv
如果在 FullInventory.csv 中找不到 EmployeeID.txt 中的 ID,则使用 EmployeeId.txt 中的数据输出 NotFound.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:\Users\Desktop\matchFound.csv" -append
}
else {
$TxtLine | Out-File -FilePath "C:\Users\Desktop\notFound.txt" -append
}
}
}
我现在遇到的问题是 matchFound.csv 文件没有输出正确的数据。我认为它从 csv 文件输出最后一个数据列而不是它匹配的那个。 任何帮助或建议都会非常感激。
这可以使用
Group-Object -AsHashtable
来实现以允许快速查找,散列键将是从 Name
列中提取的 UPN
。除了将其导出到两个不同的文件之外,您还可以使用 steppable pipeline 而不是使用 -Append
.
$map = Import-Csv $FullInventory -Delimiter "`t" |
Group-Object { [mailaddress]::new($_.UPN).User } -AsHashTable -AsString
$pipeMatch = { Export-Csv 'C:\Users\Desktop\matchFound.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:\Users\Desktop\notFound.csv" -NoTypeInformation
$pipeMatch.End()