Windows PowerShell | Where {$_.property -eq statement}

Windows PowerShell | Where-Object {$_.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-Object' 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

 ♣

PowerShell Pre-requisites and Checklist

In the case of Windows 7 and later, you don't need to download any extra files, just: 'Add Feature' --> Windows PowerShell.  However, for older operating systems, there are different versions of PowerShell for XP, Windows Server 2003 and Vista.  For such legacy systems only, you need to download PowerShell from Microsoft's site.

Once you have installed PowerShell 2.0 or later, I recommend choosing the ISE (Integrated Scripting Engine) version, it will save buying a text editor.

Example of the PowerShell 'Where-Object' Filter

A good time to add a 'Where-Object' statement is when you need to filter a list.  What we are going to do is get a list of files with GCI (Get-Childitem), and then pipe the output into a 'Where' clause, which filters the stream according to this condition: file extension equals .exe. 

Example 1a: Where clause to find executable files

# PowerShell Where-Object filter to list the exe files C:\program Files
GCI "C:\Program Files" -recurse | Where-Object {$_.extension -eq ".exe"}

Note 1: Perhaps this foible 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-Object replaced with '?'

PowerShell has aliases for the common cmdlets; '?' and 'Where' are aliases for Where-Object, you may already know gci for Get-ChildItem.

# PowerShell Where script to list exe files C:\Program Files
Clear-Host
$GuyDir = "C:\Program Files"
$FilesExe = gci $GuyDir -recurse
$List = $FilesExe | ? {$_.extension -eq ".exe"}
$List | Sort-Object -unique | Format-Table name

Learning Points for PowerShell's Where Statement

Note 3: Many PowerShell scriptwriters prefer to type a single character, namely the question mark, '?' instead of 'Where' or 'Where-Object'.  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 the file extension to filter from ".exe" to ".dll"

Challenge 2: Change: Where {$_.extension -eq ".exe"} to Where {$_.name -eq "ReadMe"}  See more on PowerShell's $_.

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:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

PowerShell 'Where' Examples That Filter WMI objects

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-Object {$_.name -Match "Network"}

Example 2b:

Gwmi -List | Where {$_.name -Match "Network"}

Note 7: I don't use many alias, but to save space I often use plain 'Where' instead of 'Where-Object'.Example 2b

Example 2c:

# PowerShell where filter to list Network WMI objects
Clear-Host
$objNetwork = Get-WmiObject -List | Where {$_.name -Match "Network"}
$objNetwork | Format-Table name

Learning Points for PowerShell's Where Statement

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

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft's operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try - it's free.

Download your free copy of WMI Monitor

Researching PowerShell's Where-Object

The where filter is so common that we tend to forget this is actually a cmdlet called Where-Object, which has two aliases, firstly the simple 'where', and secondly the question mark: '?'  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}.  Until PowerShell 3 I had never seen 'where' in isolation, only receiving input via a pipe (|).

As a result of this knowledge you can refine the output of your where clause by piping into a Sort-Object statement.

One more point to note, PowerShell uses its own comparison objects such as -gt or -le, and not > or =<.

More PowerShell Object Cmdlets

You can employ Get-Command to research more of PowerShell's 'Object' family.  I like to use the -Noun filter thus:

®

Clear-Host
Get-Command -Noun object

See more on the Get-Command itself ยป

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 like this page then please share it with your friends

 


See more PowerShell examples of 'Object' cmdlets

PowerShell Tutorials  • Syntax  • PowerShell Where-Object  • Foreach-Object  • Free WMI Monitor

  • New-Item  • Remove-Item  • ItemProperty  • PowerShell New Object   • Sort-Object   • Group-Object

PowerShell Splatting  • Select-String  • -replace string  • Compare-Object  • Measure-Object

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2017 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: