Monthly Archive

Categories

Where-Object options

You have a few Where-Object options when you want to filter data. Remember that Where-Object filters objects based on property values and Select-Object filters objects based on object position in the pipeline or array as well as filtering properties.

 

The classic way to use Where-Object is to use a filter script

PS> Get-Process | Where-Object -FilterScript {$_.CPU -gt 5}

 

You’re filtering to accept process objects where the CPU property shows more than 5 seconds of usage

 

As an aside most people don’t use the FilterScript parameter they rely on positional parameters to assign the script block to FilterScript. Script analysers such as PSScriptAnalyzer (at least as far as the rules in VScode are concerned) don’t seem to object to the use of positional parameters in this case which is rather sloppy and remiss. Another reason I don’t like any of the analysis tools I’ve tried as they aren’t consistent.

 

PowerShell then introduced a simpler syntax

PS> Get-Process | Where-Object -Property CPU -gt -Value 5

 

which is usually used via positional parameters

PS> Get-Process | Where-Object CPU -gt 5

 

which again seems to sneak past the analysers. If you want multiple clauses in the filter using –and / –or to join them you have to use the original syntax. Also note that –gt isn’t an operator – its a parameter!

 

There is also the little used array method option to filter a collection of objects

PS> (Get-Process).Where({$_.CPU -gt 5})

 

which it should be noted is much faster than Where-Object on the pipeline.

When using Where-Object remember the options and if you’re using positional parameters remember what you’re actually doing.

Comments are closed.