I need to export a custom PS object to CSV, but format it as a vertical list.
When I call
$object | Export-Csv -Path "$($env:USERPROFILE)\Desktop\out.csv" -force
or
$object | ConvertTo-Csv | clip
The output always displays the object properties horizontally, meaning when viewing them in excel we will need to scroll to the righ to view all properties.
How can I output the object to display the properties vertically?
Current Output
#TYPE System.Management.Automation.PSCustomObject
"one","two","three"
"1","2","3"
Required Output
#TYPE System.Management.Automation.PSCustomObject
"one","1"
"two","2"
"three","3"
Is this possible using PS commands, or will I have to manually build the string?
Iterate over the members of the object. Create a new custom object having 'name' and 'value' corresponding to each member you want.
Here's a simple example:
$object = [pscustomobject]@{one=1;two=2;three=3}
# not what you want
$object | ConvertTo-Csv
# what you want
$object | Get-Member -MemberType NoteProperty |
ForEach-Object {
[pscustomobject] @{Name=$_.name;Value=$object.($_.Name)}
} | ConvertTo-Csv
Perhaps a more succinct answer:
$object |
Get-Member -MemberType NoteProperty |
Select-Object @{name='Name';expression={$_.name}},
@{name='Value';expression={$object.($_.name)}} |
ConvertTo-Csv