Oliver
Oliver

Reputation: 11607

Using string replace to insert the string '$_' in powershell?

I am having trouble with string replacement in powershell. Please consider the following expression:

"replaceTarget: %rep" -replace '%rep','$_'

I expect the result of this expression to be:

replaceTarget: $_

but instead, it is

replaceTarget: replaceTarget: $rep

I assume it is because the replacement string '$_' has some other meaning in the replace function.

How can I escape the input string so that $_ can be passed in without being evaluated?

Upvotes: 1

Views: 145

Answers (2)

CB.
CB.

Reputation: 60938

try with this:

'replaceTarget: %rep' -replace '%rep','$$_'

Upvotes: 4

Loïc MICHEL
Loïc MICHEL

Reputation: 26170

you coud use the .net replace function like this : 'replaceTarget: $rep'.replace("`$rep",'$_')

Upvotes: 2

Related Questions