Powershell脚本来比较CSV

时间:2019-02-21 13:23:58

标签: powershell csv

我有几张csv excel表,看起来像这样

编辑者注意:如果您有csv,请发布该csv的文本表示!

> Get-Content .\Sheet1.csv
Name,Age
Xavier,20
Liam,19
Lisy,21

> Get-Content .\Sheet2.csv
Name,Age
Liam,19
Lisy,21
Frank,25

有人可以帮我使它工作并发布csv。

我正在尝试将csv 1中的“名称”列值与csv2:

  • 如果存在匹配项,我想将值存储在名为array 1的数组中,最后将其导出到csv。例如-Liam和Lisy
  • 如果它们不匹配,我想将值存储在array 2上,最后将其导出到csv。例如-Xavier

我的代码:

$source = Import-Csv C:\output\Source.csv 
$target = Import-Csv C:\output\Target.csv
Creating array to store vales
$match = New-Object System.Collections.ArrayList
$donotmatch = New-Object System.Collections.ArrayList
Comparing column values  
foreach ($i in $source) {
    foreach ($s in $i.name) {
        foreach ($t in $target) {
            if ($n -eq $t.name) {
                $match.Add($n)
            }
            else
            {
                $donotmatch.Add($n)
            }
        }
    }
}
$match.ToArray()
$donotmatch.ToArray()

1 个答案:

答案 0 :(得分:0)

此脚本:

$Sheet1 = Import-Csv .\Sheet1.csv
$Sheet2 = Import-Csv .\Sheet2.csv

Compare-Object $Sheet1 $Sheet2 -Property Name -PassThru |
    Select-Object * -ExcludeProperty SideIndicator | 
        Export-Csv Different.csv -NoTypeInformation

Compare-Object $Sheet1 $Sheet2  -Property Name -PassThru -IncludeEqual -ExcludeDifferent |
    Select-Object * -ExcludeProperty SideIndicator | 
        Export-Csv Equal.csv -NoTypeInformation

将产生这两个文件:

> Get-Content .\Equal.csv
"Name","Age"
"Liam","19"
"Lisy","21"

> Get-Content .\Different.csv
"Name","Age"
"Frank","25"
"Xavier","20"