Feb 05 2020 03:50 AM
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
Feb 05 2020 05:22 AM
SolutionInstead 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 }
Feb 05 2020 05:56 AM
Thank you for that - there is obviously some difference in the way that the operator and and method handle the "$" !
Feb 05 2020 06:05 AM
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:
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.
Feb 05 2020 05:22 AM
SolutionInstead 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 }