Powershell: Unexpected Behaviour using -replace vs. Replace() and inputs including $$

Created on 28 Jan 2020  路  3Comments  路  Source: PowerShell/PowerShell

hello :wave: ,

we are encountering a strange/unexpected behaviour using the -replace method in combination with $$ as the input.

Steps to reproduce

"hello world" -replace "world", '$$powershell'
"hello world".Replace("world", '$$powershell')

Expected behavior

-replace and .Replace() should behave the same -> output should be hello $$powershell

Actual behavior

output includes only a single $ character if -replace is used -> output is hello $powershell

Environment data

PSVersion                      7.0.0-rc.2
PSEdition                      Core
GitCommitId                    7.0.0-rc.2
OS                             Linux 4.19.76-linuxkit #1 SMP Thu Oct 17 19:31:58 UTC 2019
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0鈥
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
PSVersion                      6.2.4
PSEdition                      Core
GitCommitId                    6.2.4
OS                             Linux 4.19.76-linuxkit #1 SMP Thu Oct 17 19:31:58 UTC 2019
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0鈥
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
Issue-Question Resolution-Answered

All 3 comments

-replace as an operator is entirely different to the string.Replace() method that is called when you invoke the method on strings. -replace supports regular expressions, and so is beholden to all the rules and oddities that entails.

In a regular expression replacement expression, $$ is treated as an escaped (literal) $ character. This is because replacement expressions can contain tokens such as $1, which would be replaced with the contents of a match group from the match pattern.

See here for a list of supported regular expression tokens and in which cases they can apply: https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

Thank you @vexx32 !

No worries 馃檪

Details about specific operators can be found in the Get-Help about_Operators topic and a few of the other linked topics in there as well. There are a few operators that work mainly with regex. ^^

Was this page helpful?
0 / 5 - 0 ratings