archcutbank
archcutbank

Reputation: 479

powershell regex displaying variable name instead of its value during replace

$file = 'c:\temp\config.ini'
# login.ruby.authentication.key=eskimopie
$pattern = [regex] "(.*?login\.ruby\.authentication\.key)=(.*?).*"
$secret = '12345678'


$text = (Get-Content -Path c:\temp\config.ini) 
$value = $text -match "$pattern"
$text -replace "$pattern",'$1=$secret' | Set-Content config.new

The problem is it replaces the line with

login.ruby.authentication.key)=$secret (in that, it actually puts $secret instead of 12345678. I am looking for how to get this to put the value of $secret instead of the word $secret.

Upvotes: 1

Views: 538

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

When used inside single quoted literals, variables do not get expanded. You need to use double quoted string literal that allows string interpolation.

However, the first $ should not be expanded. To tell PS not to interpolate it, add a backtick before it. See about_Quoting_Rules:

To prevent the substitution of a variable value in a double-quoted string, use the backtick character (`)(ASCII 96), which is the Windows PowerShell escape character.

So, replace with "`$1=$secret" where `$1 will pass a literal $1 string to the regex engine, and $secret will get interpolated to 12345678 before passing it to the regex engine.

Upvotes: 4

Related Questions