PowerShell Basics: -Match Comparator & -Like -NotMatch -And with Code Examples

PowerShell Basics_ -Match Comparator & -Like -NotMatch -And

PowerShell’s -Match and -Like Examples

I want to show you how to filter data with PowerShell’s -Match comparator.  The scenario is that we want research WmiObjects in general, and ‘network’ classes in particular.  The problem is that listing WMI classes swamps us with hundreds of names.  Our solution will be to use a ‘Where-Object’ clause containing a comparator such as -Match or -Like.

Topics for PowerShell -Match and -Like

Differences between -Match and -Like

I think of ‘-Match’ as meaning a pure pattern match.  Whereas to me, ‘-Like’ is a more nebulous concept, consequently I am probably going to need the wildcard* symbol.  A more technical definition is as follows: -Like is just a wildcard comparison, while -Match is a regular expression, and a superset of -Like.

Example 1: The -Match Comparator in a ‘Where’ Clause

WmiObject is our parent clause for this example.  The Where-Object statement employs a comparator to find the pattern “network”.  Because we use -Match, “network” can be anywhere in the WMI object’s name.  Incidentally, this combination of ‘Where’ with ‘-Match’ is my favourite method of filtering data.


# PowerShell example to list demonstrate -Match
# Author: Guy Thomas
Clear-Host
$WMI = Get-WmiObject -List | Where-Object {$_.name -Match "network"}
$WMI
Write-Host `n $WMI.count "WMI objects contain the word network."

Learning Points

Note 1: Take special note of this important construction $_.   Dollar, underscore, dot means ‘in this data stream‘.

Note 2: Observe how I have employed PowerShell’s signature tune, namely the (|) pipe.  The purpose of the pipe is to make the output of the list obtained by GetWmiObject, the input into the Where-Object clause.

Example 2: The -Like Comparator

I have made two changes compared with Example 1; I substituted -Like for -Match and adding a wildcard* in front of network.  -Like says to me ‘sort of’, ‘fuzzy’, or ‘around about’.


# PowerShell example to demonstrate -Like
# Author: Guy Thomas
Clear-Host
$WMI = Get-WmiObject -List | Where-Object {$_.name -Like "*network"}
$WMI
Write-Host `n $WMI.count "WMI objects contain the word network."

Learning Points

Note 3: The variable $WMI.count enables us to compare these results with those of example 1; you should see that -Like produces fewer WmiObjects then -Match.  To make -Like show all the “network” object you need to add a second wildcard: “*network*”.

Guy Recommends: Free WMI Monitor for PowerShell (FREE TOOL)Solarwinds 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 for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guesswork 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.

SolarWinds WMI Monitor Download 100% Free Tool

Example 3: The -Match Comparator with an If Construction

To give you perspective, I have introduced variations, for example employing an ‘If’ construction instead of the ‘Where’ in example 1 and 2.


Clear-Host
$i=0
Get-WmiObject -List | ForEach-Object {
If($_.name -Match "System") {
Write-Host $($_.name) ; $i++
}
}
"There are $i objects containing System"

Learning Points

Note 4: Unlike ‘Where’, the ‘If’ statement needs the additional command ‘ForEach-Object’. What this does is initialize the loop containing $_.name.

Note 5: The syntax of the ‘If’ construction is (test) then {script block}

Note 6: In the line: “There are $i objects containing System”
admire how PowerShell interprets the counting variable ($i) in the middle of that text string.  This is called expanding a variable, and only works if you encase the whole command in “Double quotes”.

Example 4: More Comparators -NotMatch also -And

The simplest and most common comparator is ‘equals’.  The way you code this in PowerShell with -eq  (not =).  However, in the present examples, -eq would not be much use because effectively we would need to know the name of the specific class.  Whereas in this context we don’t know the answer, furthermore, we want to broaden our research into possible names containing ‘Win32’.

Thus let examine other comparators.  It is surprising how often the negative -NotMatch produces a neat solution to a scripting problem.  For instance, there are several WmiObjects beginning with CIM, thus one way of excluding them would be to use -NotMatch “CIM”.

Furthermore, using multiple criteria for your filter is easy once you master the deceptively simple, ‘-And’ syntax.  Just remember that you need to add a second comparator ($_.name) after the -And.


# PowerShell example to list demonstrate -NotMatch and -And
# Author: Guy Thomas
Clear-Host
$WMI = Get-WmiObject -List |`
Where-Object {$_.name -NotMatch "CIM" -And $_.name -NotMatch "__"}
$WMI
Write-Host `n $WMI.count "objects containing WMI, but not CIM or __"

Learning Points

Note 7: It would make my day if you experimented with different filters.  Substitute your ideas for “CIM”, and “__”.  Perhaps best of all would be to combine -NotMatch and -Match.

See more on measuring the speed of Where-Object

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) 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 on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

-Match Character Classes

The character classes, listed below, will broaden the search.  They are useful where you need a really wide-ranging search.  With PowerShell -Match you can use these character classes:

\w is the equivalent of:  -Match [a-zA-Z_0-9].
\d matches any digit character.
\s matches any white space character including tabs.


# -Match Character Class Example
$Guy ="Babe Ruth"
$Guy -Match "\s"

# Result PS> True

Note 8: “BabeRuth” has no space, thus would produce a False result.

There are also the reverse, or negative versions, which employ a capital letter.  (Can be hard to get a false with these!)

\W (capital W) any non-word character
\S any non-white space.
\D any non digit.

Numeric Example of -Match

Suppose you have a string and wish to extract just the numeric values; this is how to do it using [char]


# PowerShell example to extract numbers from a string
[char[]]"rd2cp30" -Match "\d"
Expected result:
2
3
0

-Match Follow-up

As usual with my scripts, the mission is to get you started.  If you want to know more about -Match, -Like and their relatives, then start with PowerShell’s own help thus:


Get-Help about_Comparison_Operators.

These help files introduce a whole world of specific terms, for example, ‘regular expression comparisons’ and ‘wildcard comparison’.  Once you need to understand such extra information, then I have succeeded in my mission of introducing you to -Match and -Like.

See more PowerShell comparison examples »

Summary of PowerShell Conditional Operators

So often we suffer from information overload. Working with PowerShell is no different, fortunately 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 obtain the desired stream of information into your script’s output.


See more examples of PowerShell syntax

PowerShell Tutorials  • Syntax  • PowerShell functions  • Plist  • RegEx  • -Com

PowerShell -confirm  • WhatIf  • -Match  • -Like  • -Online  • Where  • Free WMI Monitor

-ErrorAction  • -Replace  • Windows PowerShell  • PowerShell module directory

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.