Was trying to simplify some PowerShell string replacement code, and came across something I can't quite explain. To be clear, I know how to find a substring and replace it/transform it with another value. What I'm asking for here is an explanation of this behavior and why it doesn't work this way.
With a regular string, whether it's a variable or hard-coded, I can modify the string how I see fit after it has been rendered. For example:
($greeting = 'HELLO'.ToLower()) # ===> hello
This produces the expected output by returning a lowercase copy of the string. However, I tried this using the -replace
operator and was met with an interesting result:
$greeting -replace '\w+', '$0'.ToUpper() # ===> hello
I was expecting the matched pattern in the string to be replaced with an uppercase copy of the match, but this isn't happening. I tried a few other increasingly ugly methods to see if there was some way to get this to work but to no avail:
$greeting -replace '\w+', ('$0').ToUpper() # ===> hello
$greeting -replace '\w+', "$(('$0').ToUpper())" # ===> hello
$greeting -replace '\w+', "`$0".ToUpper() # === hello
$greeting -replace '\w+', '`$0'.ToString().ToUpper() # ===> hello
$greeting -replace '\w+', (('$0').ToString()).ToUpper() # ===> hello
I also tried -creplace
in place of -replace
for a few of these but that also didn't have any effect. Why am I unable to transform the result of a match when using PowerShell's -replace
operator?
I tested this with both PowerShell 5.1 and 7 so this behavior extends between MS PowerShell and PowerShell Core.