Search code examples
powershellexport-to-csv

How to append data from one CSV to another using Export-CSV


I have a script like the following:

$in_file = "C:\Data\Need-Info.csv"
$out_file = "C:\Data\Need-Info_Updated.csv"
$list = Import-Csv $in_file 
ForEach ( $user in $list ) {
    $zID = $user.zID
    ForEach-Object { 
        Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}} | Export-Csv $out_file -NoTypeInformation -Force
    }
}

However, I am not able to get it to output all of the results to the $out_file since it does not seem to append the data to the csv file.

Is there a way to make this append the data to a file?


Solution

  • Convert the foreach loop into a foreach-object, and move the export-csv to outside the outer foreach object so that you can pipe all the objects to the export-csv.

    Something like this (untested):

    $list | ForEach {
        $zID = $_.zID
        ForEach-Object { 
            Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}}
        }
    } | Export-Csv $out_file -NoTypeInformation -Force