Forum Discussion

BrianUK's avatar
BrianUK
Copper Contributor
Feb 05, 2020
Solved

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 

3 Replies

  • 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 

    • BrianUK's avatar
      BrianUK
      Copper Contributor

      Thank you for that - there is obviously some difference in the way that the operator and and method handle the "$" !

       

       

      dretzer 

      • dretzer's avatar
        dretzer
        Iron Contributor

        Yes. The most relevant difference here is that the String.Replace method does string replace (obviously) and the -replace operator actually uses regex replace.

        If you use the regex.replace method you would see the same effects as with the -replace operator.

         

        String.Replace:

        https://docs.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.8

         

        Regex.Replace:

        https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=netframework-4.8

         

        It can be very usefull if you want to use regex for your replace operations. But for simple string replace, you should use the method of the string object instead.

        BrianUK 

Resources