How to replace a string with a dollar sign in it in powershell

Powershell has the following line

$string = "this is a sample of 'my' text $PSP.what do you think" 

how to use the -replace function to convert a string to

 this is a sample of 'my' text Hello.what do you think 

I obviously need to somehow escape the line. Also $ PSP is not a declared variable in my script

I need to change all mentions of $ PSP for some other line

+4
source share
3 answers

Use the backtick character (above the tab key):

 $string = "this is a sample of 'my' text `$PSP.what do you think" 

To replace the dollar sign with the -replace operator, avoid its backslash:

 "this is a sample of 'my' text `$PSP.what do you think" -replace '\$PSP', 'hello' 

Or use the string.replace method:

 $string = "this is a sample of 'my' text `$PSP.what do you think" $string.Replace('$PSP','Hello)' 

this is a sample of "my" text Hello. What do you think,

+7
source

Unless you change the original string (e.g. by escaping $), this is not possible (really). Your $string does not really contain $PSP , since it is not replaced by anything in the assignment statement.

 $string = "this is a sample of 'my' text $PSP.what do you think" $string -eq "this is a sample of 'my' text .what do you think" 

has the meaning:

True

0
source

You must try

$ string = $ string.Replace ("\ $ PSP", "Hello")

or

$ string = $ string.Replace ("\ $ PSP", $ the_new_value)

or for more general use of regex

$ string = [regex] :: Replace ($ string, "\ $ \ w +", "Hello")

-one
source

Source: https://habr.com/ru/post/1394379/


All Articles