Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



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

 ♣

PowerShell Pre-requisites and Checklist

In the case of Windows 7 and Server 2008, you don't need to download any extra files, just 'Add Feature' Windows PowerShell.  However, for older operating systems, installing can be confusing because 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, I recommend choosing the ISE (Integrated Scripting Engine) version, it will save you buying a text editor.

Example of the PowerShell 'Where' Filter

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

$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 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"}  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: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft 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.

Download your free copy of WMI 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 {$_.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}.

Guy Recommends:  Solarwinds' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

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 (|).

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

More PowerShell Object Cmdlets

®

Clear-Host
Get-Command -noun object

See more on Get-Command itself

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

 


See more Microsoft PowerShell tutorials

PowerShell Tutorials  • Methods  • Cmdlets  • PS Snapin  • Profile.ps1  • Exchange 2007

Command & Expression Mode  • PowerShell pipeline (|)  • PowerShell 'where'  • PowerShell 'Sort'

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.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  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

 

Home Copyright © 1999-2012 Computer Performance LTD All rights reserved

Please report a broken link, or an error.