Forum Discussion
String replacement issue...
- Feb 05, 2020
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 }
Thank you for that - there is obviously some difference in the way that the operator and and method handle the "$" !
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.