What’s the difference between .replace and -replace in powershell?

While @Keith Hill’s answer explains the difference between Replace method and the -replace operator, to explain why you might not see the same result, it is because you are using the String.Replace method which does string replace and -replace operator uses regex replace. You can use the Regex.Replace method for this purpose and you should see the same effect:

[regex]::replace($a,'.:\\LOGROOT\\', "\\$env:computername\logroot\")

In short, the -replace operator is same as Regex.Replace (the particular overload linked above), but in general Replace() can be instance or static method that can be doing anything completely different from -replace

Leave a Comment