I am doing a string replacement in PowerShell. I have no control over the strings that are being replaced, but I can reproduce the issue I'm having this way:
> 'word' -replace 'word','@#$+'
@#word
When the actual output I need is
> 'word' -replace 'word','@#$+'
@#$+
The string $+
is being expanded to the word being replaced, and there's no way that I can find to stop this from happening. I've tried escaping the $
with \
(as if it was a regex), with backtick `
(as is the normal PowerShell way). For example:
> 'word' -replace 'word',('@#$+' -replace '\$','`$')
@#`word
How can I replace with a literal $+
in PowerShell? For what it's worth I'm running PowerShell Core 6, but this is reproducible on PowerShell 5 as well.
Instead of using the -replace
operator, you can use the .Replace()
method like so:
PS> 'word'.Replace('word','@#$+')
@#$+
The .Replace()
method comes from the .NET String class whereas the -Replace
operator is implemented using System.Text.RegularExpressions.Regex.Replace()
.
More info here: https://vexx32.github.io/2019/03/20/PowerShell-Replace-Operator/