PowerShell Cookbook

Search

Categories

 

On this page

Archive

Blogroll

Disclaimer
I work for Microsoft.

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 214
This Year: 14
This Month: 1
This Week: 0
Comments: 522

Sign In

 Wednesday, July 05, 2006
Wednesday, July 05, 2006 11:23:36 PM (Pacific Daylight Time, UTC-07:00) ( )

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

Comments [1] | | # 
Thursday, July 06, 2006 12:26:14 AM (Pacific Daylight Time, UTC-07:00)
PSMDTAG:FAQ: Is there a simpiler where?
PSMDTAG:CMDLET:UTILITY: Where-Object

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



Jeffrey Snover
Name
E-mail
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):