Idris Wishiwala Idris Wishiwala - 3 months ago 24
PowerShell Question

-replace does not replace string with "()"

I'm trying to replace a string containing parentheses in PowerShell. However, when I try this to do this it is not working.

Any idea as to where I'm going wrong? What am I suppose to do to replace a string containing

()
with
-replace
in PowerShell?

$a='Some Text with (round) brackets. This text is long.'
$ch="with (round) brackets."
$b="this text"
$a -replace $ch,$b


Output:

Some Text with (round) brackets. This text is long.

Answer

-replace useses regular expression so you have to to escape your regex:

$a='Some Text with (round) brackets. This text is long.'
$ch="with (round) brackets."
$b="this text"
$a -replace [regex]::Escape($ch),$b

Output:

Some Text this text This text is long.