Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Export-CSV ignores non-shared properties for objects, how can I get around this? [duplicate]

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!

like image 909
Michael Ellis Avatar asked Jun 08 '18 01:06

Michael Ellis


People also ask

Which of the following command is used to export data to CSV?

SQLite facilitates you to export data from SQLite database to CSV file. You can export the whole table or less according to your query. . once command is used to export data to a CSV file followed by the file path/name where you want to write the file.


1 Answers

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
like image 150
JamesQMurphy Avatar answered Oct 26 '22 16:10

JamesQMurphy