Author Posts

April 15, 2018 at 12:00 am

Appreciate an explanation in the subtle differences between "replace()" and -replace in the following code snippets, which yielded different results.
replace() in code snippet A did not work.
-replace() in code snippet B worked.

# Snippet A
foreach ($textLine in $fileContent) {
	if ($textLine -like '*memsize*') {
	    $textLine = $textLine.Replace('(\d+)','4096')
	    $NewText += $textLine
	}
	else {
		$NewText += $textLine
	}
}

# Snippet B
foreach ($textLine in $fileContent) {
	if ($textLine -like '*memsize*') {
	    $textLine = $textLine -Replace '(\d+)','4096'
	    $NewText += $textLine
	}
	else {
		$NewText += $textLine
	}
}

April 15, 2018 at 1:17 am

As far as I know the replace()-method does not work with regular expressions while the -replace operator does.

April 15, 2018 at 8:47 am

Adding to Olaf's response.
See the details here:

PSTip A difference between the –replace operator and String.Replace method
'powershellmagazine.com/2012/11/12/pstip-a-difference-between-the-replace-operator-and-string-replace-method'

Comparing RegEx.Replace, String.Replace and StringBuilder.Replace – Which has better performance?
'blogs.msdn.microsoft.com/debuggingtoolbox/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance'

April 16, 2018 at 1:38 pm

That's like .split() and -split. The first is a .net method of the String class, and the second is a powershell operator. The second can use regular expressions.