“Simple Where” as a Where-Object Shortcut

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 { $_.Handles -gt 1000 }

For this type of situation, it is easy to write a function to offload all of the syntax  to the function itself:

get-process | wheres Handles gt 1000
dir | wheres PsIsContainer

The following snippet implements the “simple where” functionality:

function wheres($property, $operator = "eq", $matchText = "$true")
   Begin { $expression = "`$_.$property -$operator `"$matchText`"" }
   Process { if(invoke-expression $expression) { $_ } }

Much better!

Note: although extremely simple, this solution can be improved.   Since we pass arbitrary input to the Invoke-Expression cmdlet, it is quite easy to make syntactic mistakes that foul up the call to Invoke-Expression.  Also, this function can be abused if you don’t fully trust the input that you pass it:

dir | wheres PsIsContainer eq 'False" -and (write-host "Hello") -and "'

Bruce Payette expands on this function (and problem) in his upcoming book, “PowerShell in Action.”

One Response to ““Simple Where” as a Where-Object Shortcut”

  1. Jeffrey Snover writes:

    PSMDTAG:FAQ: Is there a simpiler where?

    Jeffrey Snover [MSFT]
    Windows PowerShell Architect
    Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
    Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Leave a Reply