2017-07-14 158 views
2

我有2个csv文件,我想从文件A到文件B添加一个新列到一个新文件。 ATM,它不会从A取值在powershell中合并2个csv文件

文件A.csv

ID Name 

1  Peter 

2  Dalas 

文件B.CSV

Class 

Math 

Physic 

新文件将是:

ID Name Class 

1  Peter Math 

2  Dalas Physics 

这两个文件具有相同的行数。

如下面的我正在使用的代码,我想现在如何从文件中的取值,并把它放在文件B.

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


$CSV1 | ForEach-Object { 
    $Value= $_ 
    $CSV2 | Select-Object *, @{Name='Information';Expression={ $Value}} 

} | Export-Csv "C.csv" -NoTypeInformation 
+1

虽然标题建议重复内容的问题不同,因为它涉及基于它们的索引来加入**对象**(而不是文件)。考虑'$ CSV1 |加入$ CSV2 {$ LeftIndex -eq $ RightIndex)',未公开的功能:https://stackoverflow.com/questions/1848821/in-powershell-whats-the-best-way-to-join-two-tables-into -one/45483110#45483110 – iRon

回答

1

假设你的两个CSV文件中正确对齐(例如,你希望用他们的行号合并的数据,而不是由任何其他键连接),我建议如下:

$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 

说明:

  • 使用-Begin脚本块将计数器设置为0(您可以在ForEach-Object之前执行此操作,但使用-Begin将其目的很好地链接到代码块)。
  • 使用Add-Member将'Class'属性添加到CSV1中的每一行,使用CSV2中行的数组索引(并且与++一样增加该索引的行数)。
  • 使用-PassThru开关将对象返回到管道。

如果你想这样做的其他方式(B> A),你可以采取同样的方法,但需要做的是这样的:

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

实际上,我惊讶$_.Class仍然作为一个新的管道的另一端,但它似乎。

你也可以使用一个计算表达式像你最初计划,但你确实需要使用一个额外的变量来存储$Class由于额外的管道:

$CSV2 | ForEach-Object -Begin {$i = 0} { 
    $Class = $_.Class 
    $CSV1[$i++] | Select @{Name='Class';Expression={$Class}},* 
} | Export-Csv "C.csv" -NoTypeInformation 
+0

太棒了! tks这么多:) – Ender

+0

但我认为你错过了文件名。我想更改'$ CSV1 | ForEach-Object .....'到'$ CSV2 | ForEach-Object ......'。 AND'-Value $ CSV2 [$ i ++]。Class .....'to'-Value $ CSV1 [$ i ++]。Class .......'与我的问题从文件A到文件B一致:)。 – Ender

+1

我编辑了答案,显示你如何以相反的方式进行操作。 –