0

I am new to powershell scripting. I have tried to develop a script using powershell major version 5. The objective of my script is to replace few string literals in a template file, with some strings. Note that, one of the string literal is replaced by a content of a file.

$ReleaseScript =  Get-Content $SourceFile -Raw

(Get-Content $ChangeSetTemplatefile -Raw)  |  
 ForEach-Object {
$_  -replace '<insert_script_here>', $ReleaseScript  `
-replace '<username>'          , $UserName  
} 
| Set-Content $CSDestinationFile"

The above replace works fine except when the file content in $ReleaseScript itself has $_. Is there a way to have a escape character to avoid replacing the replace string content or any other way to achieve the objective ?

  • Use `$$` in a *single*-quoted replace string. See [regex reference](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx#substitutions). I'm not sure I understand the problem completely so I'm not posting this as an answer. – wOxxOm Oct 25 '16 at 04:46
  • 1
    Er, actually, to replace string literals use a string replace method: `$_.replace('string1', 'string2')` – wOxxOm Oct 25 '16 at 05:02

1 Answers1

0

-replace does regular expression matching. You need to escape regular expression special characters, something like:

$ReleaseScript =  Get-Content $SourceFile -Raw
$ReleaseScript =  [regex]::Escape($ReleaseScript)

e.g.

PS C:\> [regex]::Escape('$_')
\$_

(or, as @wOxxOm comments, string literal replace with the .Replace() string method)

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87