SOLVED

String replacement issue...

Copper Contributor

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

 

 

3 Replies
best response confirmed by BrianUK (Copper Contributor)
Solution

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 

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

 

 

@dretzer 

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=netfra...

 

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 

1 best response

Accepted Solutions
best response confirmed by BrianUK (Copper Contributor)
Solution

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 

View solution in original post