Quick Tip on the PowerShell -match Operator

Here’s a quick tip for you when using PowerShell’s -match operator. The other day I was given a script to work on which was producing some (to the naked eye) confusing results, turned out the behaviour was actually consistent when you figured out what was happening. Here’s an example:

Take the following text and store it in two variables:


$a = "This is some text. It includes (brackets)"

$b = "This is some text. It includes (brackets)"

Now compare them to each other using the -eq operator and see a True result:


$a -eq $b

The script I was looking at though was using the -match operator and this gives a False result.


$a -match $b

This is because the -match operator will carry out a match using regular expressions and the text in question includes a character ) that is special in regular expressions. Consequently, if you wish to carry out a literal match with these strings you need to escape the special characters. The characters to watch out for are \$.|?*+[()^

A couple of ways to escape them are as follows, you can either insert a \ before the special character in the string like this:


$b = "This is some text. It includes \\(brackets\\)"

$a -match $b

Or a better way in my opinion to do it is use the .Net regex escape method which will prevent you from having to amend the string:


$b = "This is some text. It includes (brackets)"

$a -match \[regex\]::escape($b)