Reputation: 155
I have the following code:
$Car = [PSCustomObject] @{
Tire = [PSCustomObject] @{
Color = "Black"
Count = 4
}
SteeringWheel = [PSCustomObject]@{
Color = "Blue"
Buttons = 15
}
}
Now I want to output the object using the Format-List cmdlet. This leads to the following edition:
Tire : @{Color=Black; Count=4}
SteeringWheel : @{Color=Blue; Buttons=15}
I would like to have the output as follows:
Tire:
Color: Black
Count: 4
SteeringWheel:
Color: Blue
Buttons: 15
The output should be dynamic. I don't want to have to manually access the individual attributes as in the following example:
$Car.Tire
$Car.SteeringWheel
Thank you so much!
Upvotes: 1
Views: 782
Reputation: 26335
We can use System.Management.Automation.PSObject.Members
to extract the members from the System.Management.Automation.PSCustomObject
. Then we can use Where-Object
to filter out members that have the System.Management.Automation.PSMemberInfo.MemberType
property equal to NoteProperty
.
$Car = [PSCustomObject] @{
Tire = [PSCustomObject] @{
Color = "Black"
Count = 4
}
SteeringWheel = [PSCustomObject]@{
Color = "Blue"
Buttons = 15
}
}
foreach ($object in $Car) {
$members = $object.PSObject.Members |
Where-Object {$_.MemberType -eq "NoteProperty"}
foreach ($member in $members) {
"$($member.Name):"
$values = $member.Value.PSObject.Members |
Where-Object {$_.MemberType -eq "NoteProperty"}
foreach ($value in $values) {
"`t$($value.Name):$($value.Value)"
}
}
}
Output:
Tire:
Color:Black
Count:4
SteeringWheel:
Color:Blue
Buttons:15
Upvotes: 1