Search code examples
powershellvariablescharacterargumentexception

Powershell handle variable with special character (open bracket)


I have a script where two variables are compared, it can happen that a variable contains open brackets without closing, like in the example. Then a System.ArgumentException occur: "...not enough closing brackets.."

$test1="Testtext"
$test2="Testtext (3x(2x0,25"
if(!($test1 -match $test2)){ "test"}

how can i deal with it?


Solution

  • -match performs regular expression matching - use Regex.Escape() to automatically escape any escapable sequence in a verbatim pattern string:

    $text = 'Text with (parens)'
    $pattern = '(par'
    
    if($text -match [regex]::Escape($pattern)){
      "It worked!"
    }