Powershell - Export-CSV and Append

John picture John · Feb 9, 2012 · Viewed 92.5k times · Source

I have a script such as 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. I have tried a number of things, ideas, and suggestions found online. None of them seem to work and I feel like I am missing something rather easy here. Is there a way to make this append the data to a file? If so, could you provide an example or a snippet of code to make it work in that manner? I am not asking for a rewrite of all of the code or anything along those lines, just a way to make the data that is being exported appended to the file that is output.

Answer

manojlds picture manojlds · Feb 10, 2012

Convert the foreach loop into a foreach-object and move the export-csv to outside the outter 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