Powershell handle variable with special character (open bracket)

519 Views Asked by At

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?

1

There are 1 best solutions below

0
Mathias R. Jessen On BEST ANSWER

-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!"
}