PowerShell: -replace, regex and ($) dollar sign woes

Question:

I am in the process of converting thousands of lines of batch code into PowerShell. I’m using regex to help with this process. The problem is part of the code is:

When replaced it just shows $2 and doesn’t expand out the variable. I’ve also used single quotes for the second portion of replace instead of escaping the variables, same result.

When replaced it just shows $2 and doesn’t expand out the variable. I’ve also used single quotes for the second portion of replace instead of escaping the variables, same result.

$2 -match "^$4 ) {`$5 }”

$replacedString

Answer:

You could try something like this:

Note the $$$2. This evaluates to $ and content of $2.


Some code to show you the differences. Try it yourself:

Source:

PowerShell: -replace, regex and ($) dollar sign woes by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply