PowerShell对比文本与CSV文件时匹配结果输出异常,求解决方案
问题描述
有两个待处理文件:
EmployeeID.txt(制表符分隔文本)内容:
Number ID 32324 KLEON 23424 MKEOK
FullInventory.csv内容:
Name URL UPN Status John http:// KLEON@COM.COM Yes
需求:通过PowerShell对比两个文件,输出两个结果文件:
matchFound.csv:若EmployeeID.txt中的ID存在于FullInventory.csv的UPN前缀(@分隔符前的部分),则输出对应FullInventory.csv的整行数据notFound.txt:若ID未匹配到,则输出EmployeeID.txt中对应的行
原代码运行后,matchFound.csv总是输出CSV文件的最后一行,而非正确的匹配行。
问题排查
原代码的核心问题:
- 判断
$array -contains $TxtID后直接使用$CSVLine,但此时$CSVLine是外层循环最后一次迭代的变量值,并非实际匹配到的那一行 - 每次遍历
EmployeeID.txt的行时都重新遍历FullInventory.csv构建数组,重复操作效率低下且逻辑错误
修正方案
优化思路:
- 先预处理
FullInventory.csv,用哈希表存储UPN前缀与对应行数据的映射,避免重复遍历 - 遍历
EmployeeID.txt时直接查找哈希表,快速定位匹配行或标记未找到
修正后的代码:
# 导入文件(确保$Global变量已正确赋值,或直接替换为文件绝对路径) $ImportTXT = Import-CSV -Path $Global:EmployeeID -Delimiter "`t" $ImportFullInv = Import-CSV -Path $Global:FullInventory # 预处理FullInventory,建立UPN前缀到对应行数据的映射哈希表 $upnPrefixMap = @{} foreach ($csvRow in $ImportFullInv) { if (-not [string]::IsNullOrEmpty($csvRow.UPN)) { $prefix = $csvRow.UPN -split "@" | Select-Object -First 1 $upnPrefixMap[$prefix] = $csvRow } } # 清空目标文件(避免多次运行追加旧数据) $matchOutputPath = "C:\Users\Desktop\matchFound.csv" $notFoundOutputPath = "C:\Users\Desktop\notFound.txt" if (Test-Path $matchOutputPath) { Remove-Item $matchOutputPath } if (Test-Path $notFoundOutputPath) { Remove-Item $notFoundOutputPath } # 遍历EmployeeID.txt的每一行进行匹配判断 foreach ($txtRow in $ImportTXT) { $targetID = $txtRow.ID.Trim() # 去除ID可能带的首尾空格,避免匹配失败 if ([string]::IsNullOrEmpty($targetID)) { Write-Host "Empty ID found in EmployeeID.txt" continue } if ($upnPrefixMap.ContainsKey($targetID)) { # 输出匹配到的CSV行到matchFound.csv $upnPrefixMap[$targetID] | Export-Csv -Path $matchOutputPath -Append -NoTypeInformation } else { # 输出未匹配的行到notFound.txt $txtRow | Out-File -FilePath $notFoundOutputPath -Append -Encoding utf8 } }
关键优化点
- 哈希表
$upnPrefixMap将匹配查找效率从O(n)提升到O(1),大幅优化性能 - 提前清空目标文件,避免多次运行导致数据重复
- 对ID执行
Trim()处理,规避因空格导致的匹配失效 - 使用
-NoTypeInformation参数导出CSV,避免生成多余的类型信息行 - 用
[string]::IsNullOrEmpty()做空值判断,逻辑更严谨
内容的提问来源于stack exchange,提问作者aasenomad
相关产品推荐
相关产品推荐

