Escape special characters with -match and -like

Let’s try comparing two identical strings.

$String = "Get-BlogPost [is super]."

$String -match $String
False

$String -like $String
False

The first result is expected, because match implements the regex function, and brackets are special characters in regex. The second result is, perhaps, more surprising. Why does like not return True in this instance? It appears that like is underpinned by regex, meaning that regex special characters must be escaped. So, let’s try escaping them:

$String -match [Regex]::Escape($String)
True

$String -like [Regex]::Escape($String)
False

The first works because [Regex]::Escape() applies escape characters that are applicable to regex:

[Regex]::Escape($String)
Get-BlogPost\ \[is\ super]\.

However, this doesn’t work with the like operator, because, although regex characters must be escaped, they must be escaped with the standard PowerShell escape character: backtick (`). To do this, use [System.Management.Automation.WildcardPattern]::Escape():

[System.Management.Automation.WildcardPattern]::Escape($String)
Get-BlogPost `[is super`].

To summarise:

$String -match [Regex]::Escape($String)
True

$String -like [System.Management.Automation.WildcardPattern]::Escape($String)
True