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
$CSV1 | Join $CSV2 {$LeftIndex -eq $RightIndex), undocumented feature of: stackoverflow.com/questions/1848821/… - iRonJoin-Objectcmdlet to better support a join on index by omitting the-Onparameter. The command to achieve the above is now simply:$CSV1 | Join $CSV2- iRon