Windows PowerShell | Where {$_.property -eq statement}
Windows PowerShell | Where {$_.property -eq statement}
I started my
computing career in 1982 with a spreadsheet called SuperCalc. One of the most useful commands that I mastered was the 'If' statement, it was brilliant at filtering data. Now, although PowerShell also
supports the 'If' statement, I find that PowerShell's 'Where' construction is much more versatile for filtering the output. Let us learn more about 'Where' by examining the following practical examples.
PowerShell Topics for the PowerShell Where Statement
Download
PowerShell from Microsoft's site. One relevant point is that there are different versions
of PowerShell for XP, Windows Server 2003 and Vista. In the case of Windows 7 and Server
2008, you don't need a download, just 'Add Feature' Windows PowerShell.
Once you have installed PowerShell 2.0, I recommend choosing the
ISE (Integrated Scripting Engine) version, it
will save you buying a text editor.
A good time to add a 'Where' statement is when you need to filter a list. What we are going to do is get a list of files with 'Get-Childitem', and then pipe the output
into a 'Where' clause, which filters according to this condition: file extension equals .exe.
Example 1a Where clause to find executable files
# PowerShell where filter to list the exe files C:\program Files Get-Childitem "C:\Program Files" -recurse | where {$_.extension -eq ".exe"}
Note 1: Perhaps this is a foible that only effects me, but whenever I create a 'Where' statement from scratch, I forget to introduce 'where' with a | pipe symbol.
Note 2: # (hash) means: 'Here follows a comment'
Example 1b Where replaced with '?'
# PowerShell Where script to list exe files C:\Program Files
Note 3: Many PowerShell scriptwriters prefer to type the single question mark character, '?' instead of 'Where'. However, I prefer to stick with the
full word 'Where' because it makes the script easier to read especially when the rest of the script is new or complex.
Note
4: If you like abbreviations, PowerShell has lots of aliases for common commands, for example, gci
for Get-ChildItem. In Example 1b we could also use 'ft' instead of format-Table.
Also, I mostly use
plain 'sort' rather than sort-Object.
Note 5: I cannot emphasise enough, always remember to introduce the where statement with a pipe, hence, ..... | where{$_......
Note
6: Observe how sorting and
formatting can improve the output. To see what I mean, compare Example 1a with Example 1b.
Challenge 1: Change ".exe" to ".dll"
Challenge 2: Change: where
{$_.extension -eq ".exe"} to where {$_.name -eq "ReadMe"}
Challenge 3: Try changing the location from C:\program files to a folder of your choice. If you accept
this challenge, also consider changing the file extension.
Guy Recommends: SolarWinds LANSurveyor
LANSurveyor will produce a neat diagram of your network topology. But that's
just the start;
LANSurveyor can
create an inventory of the hardware and software
of your machines and network devices. Other neat features include dynamic
update for when you add new devices to your network. I also love the ability to export
the diagrams
to Microsoft Visio.
Finally, Guy bets that if you take a free trial of LANSurveyor then you will
find a device on your network that you had forgotten about, or someone else
installed without you realizing!
Another situation that benefits from a 'Where' statement is when we research PowerShell's objects.
To take a network example, imagine that our goal is to display the TCP/IP properties, but
we have a problem - what is the WMI object called? Let us begin our quest by researching WMI objects. We already
know that we can use, wmiobject -list, but let us refine our search by adding a where statement.
My idea behind
providing three examples of achieving the same goal is to give you perspective,
and to illustrate that there is no one 'right' way of coding PowerShell.
Example 2a
# PowerShell where clause in WMI script Get-wmiobject -list | where {$_.name -match "Network"}
Example 2b
gwmi -list | ? {$_.name -match "Network"}
Example 2c
# PowerShell where filter to list Network WMI objects
$objNetwork = Get-WmiObject -list | where {$_.name -match "Network"} $objNetwork | Format-Table name
Learning Points for PowerShell's Where Statement
Note 7: Example 2b shows
us that you can use a question mark (?) to replace 'Where'. This example also employs the alias gwmi for Get-WmiObject.
Note
8: Most 'Where' statements employ the '{$_.xyz'
construction. What dollar underscore ($_.xyz) does is say: 'Take the xyz from the current input'.
The second half of the statement is concerned with an evaluation, which achieves the filtering we desire. In these examples I use -match, but you could substitute, -eq (equals), -like, or any other of PowerShell's comparison operators.
Note 9: One lesson that I am for ever re-learning is that every PowerShell word, symbol, or even bracket is loaded with meaning. For instance, where {requires braces, and not
elliptical brackets}.
˚
Researching PowerShell's Where-Object
The where filter is so common that we tend to forget that this is
actually a cmdlet called Where-Object, which has aliases of where and ?
My point is that you we can apply the usual PowerShell research techniques
of Get-help.
Clear-Host Get-Help Where-Object -full # Plain 'help where' also works.
Help reminds us that Where-Object does its filtering by examining a {Scriptblock}.
I have never seen where in isolation, only receiving input via a pipe (|).
One more point to note, PowerShell uses its own comparison objects such
as -gt or le, and not > or =<.
As a result of this knowledge you can refine the output of your where
clause by piping into a Sort-Object statement.
Summary of The PowerShell 'Where' Clause
One of PowerShell's greatest assets is the ability to pipe the output of one command into another command. The 'Where' clause
provides a suitable vehicle for testing this technique of piping and then filtering the output. The skill is to experiment
until you get just the list that you need.
Incidentally, mastering the 'Where' command gives you an insight into the modular nature of PowerShell. Once you master of the rhythm of the command: Output | (pipe) where {$_.property -condition
"comparison"}, then you can apply the same construction to numerous other PowerShell scripts.
See more examples of PowerShell's 'Where' clause in action:
If you see an error of any kind, do let me know. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
*
Guy
Recommends: WMI Monitor and It's Free!
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
WMI Monitor so that you can examine these gems of
performance information for free. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.