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!

The 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.

This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s