I was under impression that .replace and -replace were the exact same thing, however I found that I could not accomplish some RegEx tasks with .replace that I could with -replace. Could someone please point out what I'm missing?
Broken Regex replace:
$a=$a.Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")
Working Regex replace:
$a=$a -Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")
ps: The following URL leads me to think there are .replace options I am unfamiliar with, but I cant seem to find any additional information on how to use them, or how to access the help for these options. http://www.computerperformance.co.uk/powershell/powershell_regex.htm Regex.Replace(String, String, String, RegexOptions) and also: Regex.Replace(String, String, MatchEvaluator, RegexOptions) methods.
Thank you
They are not the same thing.
.Replace
is a .NET method either on System.String or any other type with an instance method namedReplace
.-replace
is a PowerShell operator that that uses regular expressions. Runman about_operators
to see more info on the-replace
operator.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 theString.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:In short, the
-replace
operator is same asRegex.Replace
(the particular overload linked above), but in generalReplace()
can be instance or static method that can be doing anything completely different from-replace