Search code examples
powershellstring-comparisonpowershell-5.0

Like operator returning false when string contains backtick


This might sound like a silly question but I do not understand why the presence of the backtick character fails a comparison with the Like operator.

For exemple :

> 'a' -Like 'a'
True # Seems logical to me

> '`' -Like '`'
False # Why does this return false ?

Thanks for your help


Solution

  • The backtick (`) works as an escape character for wildcard patterns in PowerShell, so the pattern ` is interpreted as just an empty string.

    Escape it like so:

    '`' -like '``'
    

    Beware that ` is also the escape character for expandable strings (ie. double-quoted string literals) in PowerShell, in which case you'd have to double-escape it:

    '`' -like "````"