Hello everyone,

I’m stuck on the last part of my powershell script, exporting a variable to a csv column. I have the following example:

$file1 = examplecsv1.csv
$file2 = examplecsv2.csv

foreach ($line in $file1) {
    foreach ($row in $file2) {
        if ($line.col1 -eq $row.col1){
            #this is the part im having issues with:
            $row.col2 | Add-Content examplecsv3.csv #how to export to col3 of examplecsv.csv?
            }
    }
}

I just want to export $row.col2 to a specific column in the examplecsv3.csv

7 Spice ups

Hey … I believe you need to use get-content

$file1 = Get-Content './examplecsv1.csv'
$file2 = Get-Content './examplecsv2.csv'

Regards

Instead of:

  $row.col2 | Add-Content examplecsv3.csv #how to export to col3 of examplecsv.csv?

try

  $row.col2= $line.col3

of course, you must save the array to a CSV.

1 Spice up

Thank you for your reply!

how would i save the array and where should i put the save array command? within the foreach loop with -append?

Export-csv
Yes, append can work

See:. Export-Csv - PowerShell - SS64.com

I’m getting nothing but errors. what is the syntax for exporting the value to col3?

 $row.col2 = $line.col3 | Export-Csv -Append

I got this from a response on stackoverflow, and explained what was going on.

$row is a reference to an object in $file2. When you update $row, $file2 is automatically updated. Therefore, you can just wait until you have made all your updates before exporting to CSV. So assuming your logic is correct for when you want to update col2 of $file2, you can do the following:

$file1 = import-csv C:\temp\csv1.csv
$file2 = import-csv C:\Temp\csv2.csv

foreach ($line in $file1) {
    foreach ($row in $file2) {
        if ($line.col1 -eq $row.col1) {
            $row.col2 = $line.col3
        }
    }
}
$file2 | Export-Csv -Path c:\Temp\NewFile.Csv -NoType

First import the CSV files properly

# Instead of 
$file1 = examplecsv1.csv
# do this
$FIle1 = Import-CSV -Path .\examplesv1.csv

then at the end:

# Export
$File2 | export-CSV -Path  '.\newcsv.csv'