Home > Net >  String -like comparison failing when it includes "`" (Acute) character in PowerShell
String -like comparison failing when it includes "`" (Acute) character in PowerShell

Time:10-27

Below comparison is giving false result in PowerShell , Want it to be true. ` operator is causing it to be false whereas for any other special character it is returning true.

> 'abc`@01' -like 'abc`@01'
False

CodePudding user response:

-like is a wildcard comparison operator and ` is a wildcard escape sequence.

PS ~> 'abc`@01' -like 'abc``@01'
True

Use -eq if you want an exact string comparison without having to worry about escaping the reference string:

PS ~> 'abc`@01' -eq 'abc`@01'
True

CodePudding user response:

To add to Mathias R. Jessen's helpful answer:

On occasion you may be dealing with strings that should become part of a wildcard expression, but themselves should be treated literally, which requires escaping the wildcard metacharacters, * ? [ ] `, with `.

[WildcardPattern]::Escape() allows you to perform this escaping programmatically (which is especially helpful if the string was passed from the outside), as shown in the following example:

# The value to use *literally* as part of a wildcard expression below.
$literalValue = '[1]'

# Escape it for use in the wildcard expression.
# -> '`[1`]'
$escapedValue = [WildcardPattern]::Escape($literalValue)

'file[1]' -like ('*'   $escapedValue) # -> $true

Regrettably, as of PowerShell Core 7.2.0-rc.1, there is a bug: ` itself, even thought it should be escaped as ``, is not escaped, which Mathias has reported in GitHub issue #16306.

In other words: with the specific wildcard pattern in your question, this technique wouldn't work.

  • Related