Skip to main content

Program: Simplify Most Where-Object Filters in Windows PowerShell

The WhereObject cmdlet is incredibly powerful, in that it allows you to filter your output based on arbitrary criteria. For extremely simple filters (such as filtering based only on a comparison to a single property), though, the syntax can get a little ungainly:

GetProcess | WhereObject { $_.Handles gt 1000 }

load all the syntax to the script itself:

GetProcess | CompareProperty Handles gt 1000 GetChildItem | CompareProperty PsIsContainer

With a shorter alias, this becomes even easier to type:

PS >gt;SetAlias wheres CompareProperty PS >GetChildItem | wheres Length gt 100

Example 23 implements this “simple where” functionality. Note that supplying a nonexisting operator as the $operator parameter will generate an error message.

Example 23. CompareProperty.ps1

############################################################################## ## CompareProperty.ps1 ## ## Compare the property you provide against the input supplied to the script. ## This provides the functionality of simple WhereObject comparisons without ## the syntax required for that cmdlet. ## ## Example: ## GetProcess | CompareProperty Handles gt 1000 ## dir | CompareProperty PsIsContainer ############################################################################## param($property, $operator = "eq", $matchText = "$true")

Begin { $expression = "`$_.$property $operator `"$matchText`"" } Process { if(InvokeExpression $expression) { $_ } }

A UK Dedicated Server provides an isolated environment for Windows-based workloads with control over the operating system, server configuration, and allocated resources.
Help Category