6

I'm saving properly using Export-CSV in powershell 2 but I want it to include everything, I want empty values if it's empty.

$list | Export-Csv -Path (Get-SaveFile) -NoTypeInformation;

The documentation for Export-CSV:

When you submit multiple objects to Export-CSV, Export-CSV organizes the file based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are not included in the file.

I can't simply organize the list either because there are two things that may have 0 or more values. For some objects there are comments, and some have links, some have both. But I need 1 column per link and 1 column per comment regardless of how many, or none, there are.

Is there a different cmdlet that achieves this export-csv style where no fields are ignored?

Edit with answer: This PowerShell Snippet from iRon was exactly what I needed to override the property truncation of Export-CSV. https://powersnippets.com/union-object/ Thanks for the help!

Michael Ellis
  • 181
  • 3
  • 15
  • It sounds like you might have to build a custom piece of code to deal with it. `Export-CSV` is probably optimised to only run one pass of the data. To treat the data differently you could run a loop using `ForEach ($item in $list) {}`, and address each object's properties using conditions. – mjsqu Jun 08 '18 at 01:35

1 Answers1

8

If you know the specific properties that you want in your CSV file, you can insert a Select-Object cmdlet into the pipeline like so:

$list | Select-Object prop1, prop2, prop3 | Export-Csv -Path (Get-SaveFile) -NoTypeInfo

If you don't know the specific properties, you can scan the list to generate a property list. Each object exposes a property named PSObject, which contains another property named Properties. You can scan over the list, grab the names of the properties of every object in the list, and then finish it with a call to Select-Object -Unique to get a nice list of property names with no duplicates.

$propList = $list | ForEach-Object {
        $_.PSObject.Properties | Select-Object -ExpandProperty Name
    } | Select-Object -Unique

$list | Select-Object $propList | Export-Csv -Path (Get-SaveFile) -NoTypeInformation
JamesQMurphy
  • 4,214
  • 1
  • 36
  • 41
  • Excellent way to gather all the property names. I get an error `Select-Object : Cannot convert System.Management.Automation.PSObject to one of the following types` so I will just use the property list to make a dummy 1st object to override the Export-CSV truncation of properties. – Michael Ellis Jun 08 '18 at 03:10