Search code examples
powershellwildcardstring-comparison

How to properly search for wildcard characters using variables in PowerShell?


When doing string comparison, the -like comparator is my usual go-to solution.

But there is one odd thing I cant wrap my head around when using wildcards with variables.

String example

This will work...

$Test = 'My string'
$Test -like "My*"

True

This will mess some things up

$Test = '[My string]'
$Test -like "[My*"

WildcardPatternException: The specified wildcard character pattern is not valid: [My*

$Test -like '`[My*'
True

Variable example

But how do I use this with a variable used as search argument?

$Test = 'My string'
$Search = 'My'

$Test -like "$Search*"

True

This will fail as [ will be parsed as part of a wildcard construction...

$Test = '[My string]'
$Search = '[My'

$Test -like "$Search*"

WildcardPatternException: The specified wildcard character pattern is not valid: [My*

I need the literal content of $Search to be used instead...

Work around

One work around is of course not to use [ in the search variable

$Test = '[My string]'
$Search = 'My'

$Test -like "*$Search*"

True

But that will of course catch more strings then [My.


Solution

  • Ok, I actually thought I tried this...
    But I must have missed this solution somehow.

    $Test = '[My string]'
    $Search = '`[My'
    
    $Test -like "$Search*"
    
    True
    

    So escaping special characters in the variable declaration do work.

    '`*'
    '`\'
    '`~'
    '`;'
    '`('
    '`%'
    '`?'
    '`.'
    '`:'
    '`@'
    '`/'
    '``'
    

    Edit

    I found out the actual issue I was having. In my own code, I was actually using a variable to define my search variable.

    $Test = '[My string]'
    
    $SearchString = 'My'
    $Search = "``[$SearchString" #I need to escape the escape character at this point...
    
    $Test -like "$Search*"
    
    True