PowerShell


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 Where statement

Instructions to run the PowerShell code:PowerShell where statement

Method 1 (Quick)

  • Launch Windows PowerShell
  • Copy the code into memory
    (For instance, from Example 1a)
  • Right-click on the PowerShell symbolPowerShell Scripts
  • Edit --> Paste
  • See the menus in my screenshot to the right
  • Press enter to execute the code

Method 2 (Best)

  • Copy the code below into a text file.
  • Save the file with a .ps1 extension, for example: network.ps1
  • In Powershell, navigate to where you saved network.ps1
  • Issue this command:
    .\network 
    (dot backslash filename)

'Where' examples which filter lists of files

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 script 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 script to list the 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

Note 1:  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 2:  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 3:  I cannot emphasise enough, always remember to introduce the where statement with a pipe, hence,
..... | where{$_......

Note 4:  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.

  ˚

'Where' examples which 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

get-wmiobject -list | where {$_.name -match "Network"}

Example 2b

gwmi -list | ? {$_.name -match "Network"}

Example 2c

# PowerShell cmdlet to list Network WMI objects
$objNetwork = get-wmiobject -list | where {$_.name -match "Network"}
$objNetwork |Format-Table name

Learning Points for PowerShell's Where

Note 1:  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 2:  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 3:  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}.

Summary of PowerShell's 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:

See Also

Windows PowerShell Home  • Introduction  • Cmdlets  • Exchange 2007  • Profile.ps1  • $_.Pipeline

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.

 *


Google

WebComputerperformance.co.uk

 

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

Please report a broken link, or an error.