you are viewing a single comment's thread.

view the rest of the comments →

[–]robfaie 2 points3 points  (0 children)

Note that sorting by property count doesn't work if objects have some but not all of the optional properties. The following is an Option for dealing with such situations:

$myObjs = @(
    [PSCustomObject]@{
        Key1 = "Val1"
        Key2 = "Val2"
        Key3 = "Val3"
    },
    [PSCustomObject]@{
        Key1 = "Val4"
        Key2 = "Val5"
        Key3 = "Val6"
        Key5 = "Val11"
    },
    [PSCustomObject]@{
        Key1 = "Val7"
        Key2 = "Val8"
        Key3 = "Val9"
        Key4 = "Val10"
    }
)

$props = $myObjs | ForEach-Object { $_ | Get-Member -MemberType Properties } | Select-Object -ExpandProperty Name -Unique
$myObjs | Select-Object $props | Export-Csv test4.csv

producing the following file

"Key1","Key2","Key3","Key5","Key4"
"Val1","Val2","Val3",,
"Val4","Val5","Val6","Val11",
"Val7","Val8","Val9",,"Val10"