Windows PowerShell - Conditional Operators

Introduction to PowerShell Conditional Operators

I think of PowerShell's conditional operators as data filters.  Perhaps you are suffering from a common problem - too much information?  If so, then choosing the most suitable PowerShell operator: -Match, -Like or -Contains will help you to distil the key facts.

Introduction to: -Match -Like and -Contains

-Match, -Like and -Contains are all similar PowerShell conditional operators, yet each has a subtle specialization.  My advice is keep experimenting until you find the particular conditional operator that suits your circumstance.  Have faith that you will be able to manipulate your data with one of this trio, and thus achieve the degree of pattern matching that you seek.

Topics for PowerShell's Conditional Operators

Please note: the above operators are in addition to the ubiquitous comparison operators, -eq, 'If' and 'ElseIf'.

 ♣

Example 1: -Match Conditional Operator

The 'match' can be anywhere within the string.  Moreover, the pattern does not have to be a complete, and this is the biggest benefit of match.  -Match can use regular expressions for pattern matching.  Incidentally -Match, and the other PowerShell conditional operators, all have a negative form, for example -NotMatch.

Example 1a - Match does not have to be at the beginning

$Person ="Guy Thomas 1949"
$Person -Match "Th"

# Result PS> True

Example 1b - Naturally a completely wrong name is no good

$Person ="Guy Thomas 1949"
$Person -Match "Guido"

# Result PS> False

Example 1c - Wrong date

$Person ="Guy Thomas 1949"
$Person -Match "1939"

# Result PS> False

Note 1: While Guy Thomas 1949 has '19', it does not have '1939', thus returns False.

Example 1d - Wildcard?  Rides to the rescue

$Person ="Guy Thomas 1949"
$Person -Match "19?9"

# Result PS> True

Note 2:  Now that we introduce the wildcard ? in the 3rd position, and given that we get a match for the other 3 digits, the result is now 'True'.

Example 1e - WmiObject and Where, using * as a Wildcard

Here is a real-life -Match example using WmiObject and a where clause, observe the Wildcard*.

Get-WmiObject -List | Where {$_.name -Match "cim*"}

Negative -NotMatch

For negative conditions, there is an alternative form called -Notmatch.

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

Additional PowerShell Character Classes for -Match

A character class, listed below, is a broader form of wildcard, they represent an entire group of characters.  You can use these for really wide-ranging searches.  PowerShell recognizes the following character classes:

\w matches any word character, meaning letters and numbers.
\s matches any white space character, such as tabs, spaces, and so forth.
\d matches any digit character.

# PowerShell Character Class Example
$Person ="Guy Thomas 1949"
$Person -Match "\w"

# Result PS> True

Note 3: Too easy!  Guy and Thomas are words.  \w is the equivalent of using
-Match [a-zA-Z_0-9]

Challenge: Try -Match "\s" on "Guy Thomas" and then on "GuyThomas"

See more on PowerShell's -Match comparisons »

Example 2: -Like Conditional Operator

With PowerShell's -Like, both sides of the expression have to be the same, fortunately, you can employ the usual wildcards * and ?

Example 2a - Having only part of the string is no good for -Like

$Person ="Guy Thomas 1949"
$Person -Like "Th"

# Result PS> False

Note 4:  Substitute -Match for -Like and the result would be 'True'.

Example 2b - Just the start of the string not enough

®

$Person ="Guy Thomas 1949"
$Person -Like "Guy"

# Result PS> False

Example 2c - Wildcard * is useful for -Like

$Person ="Guy Thomas 1949"
$Person -Like "Guy*"

# Result PS> True

Example 2d - Wildcard*  but the rest has to be correct

$Person ="Guy Thomas 1949"
$Person -Like "Gzkuy*"

# Result PS> False

Note 5:  Wildcards return more positives, but the base part must be correct.  In this instance 'Gzkuy' is not good enough to return 'True'.

Example 2e - * Wildcards *  Double wildcards are handy with -Like

$Person ="Guy Thomas 1949"
$Person -Like "*Th*"

# Result PS> True

If your logic needs the negative, then try -NotLike.  In addition, -Like has a variant that forces case sensitivity. -Clike. 

See more comparisons with PowerShell's -Like »

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11

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

The Difference Between PowerShell's -Like and -Match

$Person ="Guy Thomas 1949"
$Person -Like "Th*"

# Result PS> False

$Person ="Guy Thomas 1949"
$Person -Match "Th*"

# Result PS> True

Note 6: $Person -Like "*Th*".  The double *xyz* results in: True.

Example 3: -Contains PowerShell Conditional Operator

The conditional operator -Contains is similar to -eq, except it returns 'True' or 'False'.  -Contains is designed for situations where you wish to test for one particular item in a collection, array or a hashtable.

Example 3a  -Contains checks each item between the commas

# PowerShell -Contains
$Name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$Name -Contains "Alicia Moss"

# Result PS> True

Example 3b  -Contains requires exact equality

# PowerShell -Contains
Clear-Host
$Name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$Name -Contains "Jones"

# Result PS> False

Note: -Contains examples such as this often catch me out; for positive result you need the full name: -Contains "Jennifer Jones"

Example 3c - Wildcards are a waste of time with -Contains

# PowerShell -Contains
$Name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$Name -Contains "*Jones"

# Result PS> False

Conclusion: -Contains requires an exact match, and wildcards don't help as they do with -Match and -Like.

See more on PowerShell's -Contains »

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer's Toolset v10

This Engineer's Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it's like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer's Toolset now!

Download your fully functional trial copy of the Engineer's Toolset v10

About_Operators

# For even more information about PowerShell Operators try:

Get-Help about_Operators

Here is a List of the Types of PowerShell's Operators

  • Arithmetic (+ * - /)
  • Assignment (= also -= +=)
  • Comparison ( -Match -Like.  Also: -eq -gt)
  • Logical ( -And -Not)
  • Redirectional ( >
  • Split and Join ( -split)
  • Type (-Is -Isnot)
  • Unary ($i++)

Summary of PowerShell Conditional Operators

So often we suffer from information overload.  Working with PowerShell is no different, however, it does supply three conditional operators to filter your information: -Match, -Like and -Contains.  Each operator has different properties; with research, you can get just the filter you need, and thus filter the desired stream of information into your script's output.

If you like this page then please share it with your friends

 


See more Windows PowerShell flow control examples

PowerShell Home  • PowerShell If Statement  • PowerShell ElseIf   • Free Permissions Analyzer

Conditional Operators  • PowerShell -Match  • PowerShell -Like  • PowerShell -Contains

PowerShell Comparison Operators  • PowerShell Syntax   • Where Filter  • PowerShell Else

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-2014 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: