Was doing something like the following in one of my scripts:
1 |
$outputObjArray | ForEach-Object{ [PSCustomobject]$_ } | Export-CSV -NoTypeInformation $reportFileName |
This takes an array of hash tables and export them into a CSV. Unfortunately (and thankfully, coz I almost missed it!) some of the columns were missing in the CSV file. They appeared fine if I skipped the Export-Csv
and looked at the output on screen, but in the file columns were missing.
Turns out this is because Export-Csv
goes with the “columns” defined by the first element in the array, so anything not in that element is skipped for all the others. See this SO post for an explanation and some examples.
One workaround is to create a list of attributes across all the elements and then do a Select-Object
.
1 2 3 4 5 6 7 8 9 10 |
$attributesArray = [System.Collections.ArrayList]@() foreach (...) { # do things; and also add the hash table column to the above array if not present if ($attributesArray -notcontains "$attribute") { $attributesArray.Add("$attribute") | Out-Null } # more stuff, including adding to the array } $outputObjArray | ForEach-Object{ [PSCustomobject]$_ } | Select-Object $attributesArray | Export-CSV -NoTypeInformation $reportFileName |
One learns… :)