views:

267

answers:

2

I am trying to replace a sentence in .config file using powershell.

${c:Web.config} = ${c:Web.config} -replace

'$BASE_PATH$\Test\bin`$Test_TYPE`$\WebTest.dll' , 'c:\program Files\example\webtest.dll'

Everytime I try to run the above code I get

"Invalid regular expression pattern: $BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll" at c:\tests\runtesting.ps1 -replace <<<< $BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll

If I don't use the backtick the dollar signs will disappear and some text.

How would I pass dollar signs in a string to -replace?

A: 

This is about how to escape regexes. Every special character (special with regards to regular expressions) such as $ should be escaped with \

'$A$B()[].?etc' -replace '\$|\(|\)|\[|\]|\.|\?','x'
'$BASE_PATH$\Test\bin$Test_TYPE$\WebTest.dll' -replace '\$BASE_PATH\$\\Test\\bin\$Test_TYPE\$\\WebTest.dll','something'

The backtick would be used when the regex would be like this:

'$A$B' -replace "\`$",'x'
stej
When I tried your example it worked perfectly, but when i tried it on my code as follow, had no luck.1) '\$BASE_PATH\$\Test\bin\\$Test_TYPE\$\WebTest.dll' , 'c:\program Files\example\webtest.dll'2) "\`$BASE_PATH\`$\Test\bin\\`$Test_TYPE\`$\WebTest.dll" , 'c:\program Files\example\webtest.dll'
Ozie Harb
Before submitting my comment the second option had the backslashs right after backtick...but now they are not showing.
Ozie Harb
Tried the following and worked after adding a (slash + backtick) before a dollar sign and another backslash before an existing back slash, opened and closed the string with double quotes...-replace "\`$BASE_PATH\`$\\Test\\bin\\\`$Test_TYPE\`$\\WebTest.dll"
Ozie Harb
'"\`$BASE_PATH\`$\\Test\\bin\\\`$Test_TYPE\`$\\WebTest.dll"'
Ozie Harb
I edited the code so the string `'$BASE_PATH$\Test\bin$Test_TYPE$\WebTest.dll'` gets properly replaced.
stej
A: 

To Pass:

$BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll

Change to:

`"\`$BASE_PATH\`$\\Test\\bin\\\`$Test_TYPE\`$\\WebTest.dll"`

Logic:

  • Before every dollar sign enter \`
  • Before every backslash enter another back slash \
  • Close string with double quotes ""
Ozie Harb