Reputation: 2835
I am returning a lot of data I would like to filter. The names of the property have this information. I am used to filtering based on | ? {$_.Name -eq 'Value'}
. I would expect to be able to use the hidden .pscustomobject
to do this more dynamically.
$x = [pscustomobject]@{
atruevalue = 'sometext'
afalsevalue = 'sometext'
}
$x | ?{$_.psobject.Properties.Name -like '*true*'}
I expect this to return:
> atruevalue
> ----------
> sometext
However, it simply returns every item in the object.
Could anyone explain this behavior?
Upvotes: 4
Views: 3959
Reputation: 440092
Bruce Payette's helpful answer shows the simplest solution.
As for:
Could anyone explain this behavior?
?
, a built-in alias for the Where-Object
cmdlet, acts as a filter, which means that if the filter condition in the form of an evaluated-for-each-input script block ({ ... }
) evaluates to $True
, the input object at hand (represented as $_
inside the script block) is passed through as-is.
To put it differently: it is immaterial what specific properties of the input object your script block examines - if the condition evaluates to $True
, the whole input object is passed through.
Upvotes: 2
Reputation: 2639
If you really do want to filter the properties, then moving things around a bit will do it. This would look like:
$x.psobject.Properties | ? {$_.Name -like '*true*'}
If you just want the values rather than the properties, then add another stage to the pipeline:
$x.psobject.Properties | ? {$_.Name -like '*true*'} | % Value
Upvotes: 5
Reputation:
The Where-object filters Rows of the input, what your example does.
To Filter columns you need Select-Object.
$x = [pscustomobject]@{
atruevalue = 'sometext'
afalsevalue = 'sometext'
atruenightmare = 'someothertext'}
> $x|select ($x.psobject.properties|? name -like '*true*').Name
atruevalue atruenightmare
---------- --------------
sometext someothertext
Upvotes: 3