Simplify Most Where-Object Filters

The Where-Object 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:

        Get-Process | Where-Object { $_.Handles -gt 1000 }

For this type of situation, it is easy to write a script (as shown in Example 2-3) to offload all the syntax to the script itself:

        Get-Process | Compare-Property Handles gt 1000
        Get-ChildItem | Compare-Property PsIsContainer

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

        PS >Set-Alias wheres Compare-Property
        PS >Get-ChildItem | wheres Length gt 100

Example 2-3 implements this “simple where” functionality. Note that supplying a non-existing operator as the $operator parameter will generate an error message.

Example 2-3. Compare-Property.ps1

Code View: Scroll / Show All

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

Begin { $expression = "'$_.$property -$operator '"$matchText'"" }
Process { if(Invoke-Expression $expression) { $_ } }


                                        

For more information about running scripts see Section 1.1, “Run Programs, Scripts, and Existing Tools.”

Tags: , , , , , ,