Merge 2 csv files in powershell [duplicate]

血红的双手。 提交于 2019-12-06 07:15:19

Assuming that your two CSV files are correctly aligned (e.g you want to merge the data based on their row numbers and aren't linking by any other key) I suggest the following:

$CSV1 = Import-Csv ".\A.csv"
$CSV2 = Import-Csv ".\B.csv"

$CSV1 | ForEach-Object -Begin {$i = 0} {  
    $_ | Add-Member -MemberType NoteProperty -Name 'Class' -Value $CSV2[$i++].Class -PassThru 
} | Export-Csv "C.csv" -NoTypeInformation

Explanation:

  • Uses a -Begin script block to set a counter to 0 (you could do this before the ForEach-Object but using -Begin nicely links its purpose to the code block).
  • Uses Add-Member to add the 'Class' property to each line in CSV1, using the Array index of the line in CSV2 (and incrementing that index as it does it with ++).
  • Uses the -PassThru switch to return the object to the pipeline.

If you want to do it the other way around (B > A) you could take the same approach but would need to do it like this:

$CSV2 | ForEach-Object -Begin {$i = 0} {
    $CSV1[$i++] | Add-Member -MemberType NoteProperty -Name 'Class' -Value $_.Class -PassThru 
} | Export-Csv "C.csv" -NoTypeInformation

I'm actually surprised $_.Class still works as its the other side of a new pipeline but it seems to.

You can also use a calculated expression like you originally planned to, but then you do need to use an extra variable to store $Class due to the extra pipeline:

$CSV2 | ForEach-Object -Begin {$i = 0} {
    $Class = $_.Class
    $CSV1[$i++] | Select @{Name='Class';Expression={$Class}},*
} | Export-Csv "C.csv" -NoTypeInformation
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!