August 12th, 2008

When NOT To Use "WHERE"

PowerShell Team
PowerShell Team

I’ve seen a number of scripts that look like this:

 GET-XXXX | Where {$_.name -eq “foo”} 

or

GET-XXXX | Where {$_.name -like “A*”}

Whenever you see code like this, it is a sign that the GET-XXXX is not designed correctly.   (NOTE:  GET-XXXX is NOT a porn retrieval cmdlet – it is a standin for any GET-<SOMETHING> cmdlet).

The whole point of a cmdlet is to think about the USER and deliver the correct experience.  As a GENERAL rule, we encourage cmdlet developers to leverage PowerShell utilities like WHERE, SORT, FORMAT, etc and NOT to put that function into their cmdlets.  The reason for this is that this makes the cmdlet more complicated and provides NEW semantics that the user has to learn.

There are a couple of exceptions to this general rule:

  1. GET cmdlets should support -NAME.  A VERY large percentage of the time people do a GET, they want a specific item or a set of NAMED items so you should hotrod this experience by directly supporting it.
    • NAME should take a multiple inputs and support wildcards. e.g.  “get-process -name *ss,a*”
  2. GET cmdlets should support -FILTER if your getter has native query capabilities.  Users can decide whether the perf advantage of your cmdlet is worth learning the new syntax [in most cases it will be].
    • e.g.  If/when there are a set of AD cmdlets, they should support -FILTER and take an LDAP query. 
    • The APIs that support Get-Process have no native filtering which is why it doesn’t support it but the file system APIs do which is why “DIR -FILTER A*” works.

Cheers!

Jeffrey Snover [MSFT]
Windows Management Partner 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

Category
PowerShell
Topics
HowTo

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.