PowerShell对比两个CSV文件并添加结果列的实现问题
对比两个CSV文件并生成精准匹配结果
需求说明
需要对比Master.csv和Site.csv两个CSV文件,生成包含单独result列的结果:
- 精准定位特定列的不匹配细节
- 识别
Site.csv存在但Master.csv缺失的记录 - 识别
Master.csv存在但Site.csv缺失的记录
原代码因按索引匹配记录,无法满足需求,以下是修正后的实现:
修正后的PowerShell代码
# 模拟导入Master.csv数据 $masterData = ConvertFrom-Csv @' site, name, description, detection New York, Test1, Testing Something, "" New York, Test2, Doing Something, "" New York, Test3, "" , TRUE New York, Test4, "" , "" New York, Test6, bla bla , FALSE '@ # 模拟导入Site.csv数据 $siteData = ConvertFrom-Csv @' site, name, description, detection London, Test1, Testing Something, "" London, Test5, "", "" London, Test3, "", "" London, Test2, Doing Someth, TRUE '@ # 将Master数据按name建立哈希表,方便快速查找 $masterLookup = @{} foreach ($item in $masterData) { $masterLookup[$item.name] = $item } # 将Site数据按name建立哈希表 $siteLookup = @{} foreach ($item in $siteData) { $siteLookup[$item.name] = $item } $results = @() # 处理Site.csv中的所有记录,对比Master.csv foreach ($siteItem in $siteData) { $resultMessage = @() $masterItem = $masterLookup[$siteItem.name] if (-not $masterItem) { $resultMessage += "记录 '$($siteItem.name)' 在Master中缺失" } else { # 对比description列 if ($siteItem.description -ne $masterItem.description) { $resultMessage += "描述不匹配:Master值为 '$($masterItem.description)'" } # 对比detection列(统一大小写避免匹配问题) if ($siteItem.detection.ToLower() -ne $masterItem.detection.ToLower()) { $resultMessage += "检测值不匹配:Master值为 '$($masterItem.detection)'" } # 如果没有不匹配项 if (-not $resultMessage) { $resultMessage += "两边完全匹配(London 和 New York)" } } $results += [PSCustomObject]@{ site = $siteItem.site name = $siteItem.name description = $siteItem.description detection = $siteItem.detection Results = $resultMessage -join ', ' } } # 处理Master.csv中存在但Site.csv缺失的记录 foreach ($masterItem in $masterData) { if (-not $siteLookup[$masterItem.name]) { $results += [PSCustomObject]@{ site = $masterItem.site name = $masterItem.name description = $masterItem.description detection = $masterItem.detection Results = "记录 '$($masterItem.name)' 在Site中缺失" } } } # 输出结果 $results
预期输出
site : London name : Test1 description : Testing Something detection : Results : 两边完全匹配(London 和 New York) site : London name : Test5 description : detection : Results : 记录 'Test5' 在Master中缺失 site : London name : Test3 description : detection : Results : 检测值不匹配:Master值为 'TRUE' site : London name : Test2 description : Doing Someth detection : TRUE Results : 描述不匹配:Master值为 'Doing Something', 检测值不匹配:Master值为 '' site : New York name : Test4 description : detection : Results : 记录 'Test4' 在Site中缺失 site : New York name : Test6 description : bla bla detection : FALSE Results : 记录 'Test6' 在Site中缺失
内容的提问来源于stack exchange,提问作者Hank
相关产品推荐
相关产品推荐

