Romz
Romz

Reputation: 1457

PowerShell: Escape characters in Replace and Contains operations

I'm trying to replace all occurrences of $(foo)\bar with $(foo)\baz\bar literal string, I don't need to expand anything and I don't need to use regex.

This is my code:

if($myString.contains("$(foo)\bar\"))
{
    $myString = $myString -replace "$(foo)\bar\","$(foo)\baz\bar\"
    ...
}

It doesn't work, I'm totally lost how, when and where to escape characters like $, (, \ . Should I use single or double quotes in strings?

This is my attempt:

if($myString.contains("`$(foo)\\bar\\"))
{
    $myString = $myString -replace '\$(foo)\\bar\\','\$(foo)\\baz\\bar\\'
    ...
}

Upvotes: 1

Views: 808

Answers (1)

restless1987
restless1987

Reputation: 1598

The -replace command always works with regex. You could either escape the string correctly or just use the .replace-method of the string object. The method does not use regex, so no escaping is needed:

if($myString.contains("`$(foo)\\bar\\"))
{
$myString = $myString.replace( '$(foo)\bar\','$(foo)\baz\bar\')
...
}

Upvotes: 1

Related Questions