I recently ran into a problem with the PowerShell
like operator that I wanted to share since
what’s occurring may not be immediately apparent.
like operator allows for comparison tests of strings using wildcard characters instead of
exact matches. I think of it being similar to the match operator except
like uses simple wildcards
instead of regular expressions.
'Microsoft Windows 10 Enterprise' -like '*Windows 10*'
Easy enough, right? A string on the left and another string with wildcards on the right. If it matches, true is returned otherwise if it doesn’t match, false is returned.
The dilemma is when you decide to use wildcard characters on the left side instead of on the right:
'*Windows 10*' -like 'Microsoft Windows 10 Enterprise'
Conventional wisdom would make you think that either of these examples would return true but as you can see in the previous set of results, don’t make assumptions otherwise you could spend countless hours troubleshooting a larger script or function where something like the second example is used and it could cost you a lot of time as well as your sanity.
The characters listed in the
help topic have special meaning when used on the right side of the
like operator. If they’re used
on the left side of the
like operator, they’re literals and have no special meaning.
Their special meaning can be escaped on the right side of the
like operator using the backtick
character as mentioned in the
'Microsoft Windows 10 Enterprise' -like '`*Windows 10`*'
help topic to learn more about the PowerShell
like operator. Also consider taking a look at the
help topic to learn more about advanced wildcards that can be used with the
like operator such as
a range of characters.