Forum Discussion

BrianUK's avatar
BrianUK
Copper Contributor
Feb 05, 2020

String replacement issue...

Hi all - this issue has me pulling my hair out! Im trying to replace a string in a file, the string is " {$MY_SCHEMA}" 

 

$oldString = '{$MYSCHEMA}'
$newString = "BRIAN"
Write-Host "Replacing $oldString With $newString"
Get-ChildItem $directory -Recurse -Include "*.$fileExt" |
ForEach-Object { (Get-Content $_.FullName) |
ForEach-Object {$_ -replace $oldString, $newString} |
Set-Content $_.FullName }

 

The problem is that it fails because there is a $ symbol in $oldstring... I have tried various ways of escaping the $ but to no avail. Any clues please?

 

🙂 Brian

 

 

  • Instead of using the "-replace" operator, try using the replace method of the string object. This way you don't have to do a second foreach either:

     

    $oldString = '{$MYSCHEMA}'
    $newString = 'BRIAN'
    Write-Host "Replacing $oldString With $newString"
    Get-ChildItem $directory -Recurse -Include "*.$fileExt" |
    ForEach-Object { (Get-Content $_.FullName).Replace($oldString, $newString) |
    Set-Content $_.FullName }

    BrianUK 

  • dretzer's avatar
    dretzer
    Iron Contributor

    Instead of using the "-replace" operator, try using the replace method of the string object. This way you don't have to do a second foreach either:

     

    $oldString = '{$MYSCHEMA}'
    $newString = 'BRIAN'
    Write-Host "Replacing $oldString With $newString"
    Get-ChildItem $directory -Recurse -Include "*.$fileExt" |
    ForEach-Object { (Get-Content $_.FullName).Replace($oldString, $newString) |
    Set-Content $_.FullName }

    BrianUK 

Resources