6

I'm making a simple powershell script to replace SubWCRev in our environment. So I have a lot of template files containing variables like $WCREV$ and so forth.

I'm can't do a simple find and replace on those variables though.. I'm unable to escape the $-character properly.

The find-and-replace is simple;

function FindAndReplace {
param(
    [string]$inputFile, 
    [string]$outputFile,
    [string]$findString, 
    [string]$replaceString)
    (Get-Content $inputFile) | foreach {$_ -replace $findString, $replaceString} |
    Set-Content $outputFile
}

And I've tried many alternatives for the $findString..

Tried;

$findString = '$WCREV$'
$findString = '`$WCREV`$'
$findString = "`$WCREV`$"
$findString = "$WCREV$" 

Can't make any of it work. If I try just WCREV it replaces it alright, but then I'm left with the $ of course.. I guess I could modify my templates but it seems like a silly little problem so it's probably doable, right?

1 Answer 1

6

You are using -replace which supports regex. $ is the end of line anchor there. If you don't need regex then just use the string method replace instead.

$findString = '$WCREV$'
(Get-Content $inputFile) | foreach {$_.replace($findString,$replaceString)}

To make your original $findString with your code then you would need to use regex escape characters which is the backslash for PowerShell it is the backtick like you were trying. The single quotes is important to prevent PowerShell from attempting to expand the string as a variable. Either of the following would work but my first snippet is what I suggest.

$findString = '\$WCREV\$'
$findString = [regex]::Escape('$WCREV$')
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks! :) (I should've read the documentation a bit more...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.