I have a list of objects that can have an unknown set of properties like this:
$list = @(
[pscustomobject]@{ Name='Pork'; Type='Meat' },
[pscustomobject]@{ Name='Orange'; Type='Fruit'
SubType='Berry' ## extra property
},
[pscustomobject]@{ Name='Peanut'; Type='Nut'
Salty=$true ## extra property
},
[pscustomobject]@{ Name='Gumball'; Type='Candy'
$Foo.Name = $Foo.Value ## extra property with unknown name
}
)
It's not a "good" data structure, but it's something I run into now and then when doing things like Add-Member
in reports, searching through WMI, or dealing with other cmdlets that can return multiple similar object types.
The problem I have is in displaying all the objects in a table and/or exporting them, like to a CSV. Many cmdlets like Select-Object
only include the members of the first object in the list, and leave out other properties:
$list | Format-Table -Property * ## only displays first object's properties: Name,Type
Name Type
---- ----
Pork Meat
Orange Fruit
Peanut Nut
Gumball Candy
# other examples:
$list | Get-Member ## Only lists two NoteProperties
$list | Select-Object -Property * ## same as Format-Table
$list | Export-Csv test.csv ## only exports first two properties
## Actually does display all properties:
$list | Format-List
If I know my data might come in this way, what can I do to "fix" it before continuing? For example, how could I force $list | Export-Csv
to include all properties?