Beware of -match

by Sep 27, 2022

The -match operator is frequently used in scripts however not everyone seems to understand how it really works. It can be a really dangerous filter operator.

Let’s first create some sample data:

$list = 'ServerName, Location, Status
Test1, Hannover, Up
Test2, New York, Up
Test11, Sydney, Up' | ConvertFrom-Csv 

$list

The result is a list of hypothetical servers:

 
ServerName Location Status
---------- -------- ------
Test1      Hannover Up    
Test2      New York Up    
Test11     Sydney   Up    

Let’s assume you want a PowerShell script to pick a server from the list and manipulate it, i.e. power it down:

# server to work with:
$filter = 'Test2'
# pick filter from list:
$list | Where-Object ServerName -match $filter

All seems to work just fine:

 
ServerName Location Status
---------- -------- ------
Test2      New York Up  

However, -match is expecting a regular expression and not just plain text. Plus it returns $true if the match was found anywhere in the text. When you change $filter to “Test1” to pick server “Test1”, here is the result:

 
ServerName Location Status
---------- -------- ------
Test1      Hannover Up    
Test11     Sydney   Up  

You would have accidentally picked two servers because “Test11” also contains the text “Test1”.

Even worse: if for some dumb reason $filter is left blank, you would select everything – because “blank” is matching anything. Try yourself and set $filter to value ‘’.

Be very careful when picking comparison operators, and be extra careful with -match. In the example above, the -eq operator (equals) would have been much more appropriate, and if you must use wildcards, -like would be a lot more explicit because it requires an explicit “*” wildcard if you really want to compare only against parts of the value.

 


Twitter This Tip! ReTweet this Tip!