Escape Wildcards

When you use the –like operator, it supports three wildcards: “*” representing any number of any characters, “?” representing one character, and “[a-z]” for a list of characters. In addition, and this is not widely known, it supports the PowerShell escape character “`” that you can use to escape the wildcards.

So when you check for “*” in a string, this line works but is actually wrong:

'*abc' -like '*abc'

It is wrong because it would also return true in this case:

'xyzabc' -like '*abc'

Since you want to check for “*” and not use it as a wildcard, it needs to be escaped:

 
PS> '*abc' -like '`*abc'
True

PS> 'xyzabc' -like '`*abc'
False
 

And should you want to use double-quotes, don’t forget to escape the escape:

 
# wrong:
PS> "xyzabc" -like "`*abc"
True

# correct:
PS> "xyzabc" -like "``*abc"
False

PS> "*abc" -like "``*abc"
True

PS>  
 

Twitter This Tip! ReTweet this Tip!