Reputation: 13191
I have some objects in a pipeline, something like this:
$arr1 = @(
(New-Object -TypeName psobject -Property @{'objname'='obj1';props=@((new-object -typename psobject -Property @{'pname'='prop1';'val'=11;}),(new-object -typename psobject -Property @{'pname'='prop2';'val'='xx';}))}),
(New-Object -TypeName psobject -Property @{'objname'='obj2';props=@((new-object -typename psobject -Property @{'pname'='prop2';'val'='yy';}),(new-object -typename psobject -Property @{'pname'='prop3';'val'=22;}))})
)
$arr1 | select objname, props
Result:
objname props
------- -----
obj1 {@{val=11; pname=prop1}, @{val=xx; pname=prop2}}
obj2 {@{val=yy; pname=prop2}, @{val=22; pname=prop3}}
I need to expand props and list every expanded property alongside object name. Nothing simpler:
$arr1 | select objname -ExpandProperty props
Result:
val pname objname
--- ----- -------
11 prop1 obj1
xx prop2 obj1
yy prop2 obj2
22 prop3 obj2
So far so good. The problems start when some of the objects in the pipeline have no props:
$arr2 = @(
(New-Object -TypeName psobject -Property @{'objname'='obj1';props=@((new-object -typename psobject -Property @{'pname'='prop1';'val'=11;}),(new-object -typename psobject -Property @{'pname'='prop2';'val'='xx';}))}),
(New-Object -TypeName psobject -Property @{'objname'='obj2';props=@()})
)
$arr2 | select objname,props
Result:
objname props
------- -----
obj1 {@{val=11; pname=prop1}, @{val=xx; pname=prop2}}
obj2 {}
Now I would expect, that command:
$arr2 | select objname -ExpandProperty props
Would return result like this (no extra props for obj2, but it's still in the pipeline with it's "default" property objname):
val pname objname
--- ----- -------
11 prop1 obj1
xx prop2 obj1
obj2
Instead obj2 is missing:
val pname objname
--- ----- -------
11 prop1 obj1
xx prop2 obj1
Why ExpandProperty won't leave my object alone if there's nothing to expand?
Upvotes: 4
Views: 547
Reputation: 1459
So this is an interesting usage of ExpandProperty. In the Documentation it states that "If the Property parameter is specified, Select-Object will attempt to add each selected property as a NoteProperty to every outputted object." (https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-3.0)
So what's happening is you're telling it select the objname property from the $arr2 array, and add it as a note property to each item in props when you expand. The reason you're not seeing obj2 is because it has no props, so there's no objects to add the objname to.
Granted this makes no sense, and I did a double-take when I read the doc. Maybe someone else can enlighten me as to why they added this behavior. It's weird. This is why it looks this way though.
Upvotes: 1