Brad.Smith
Brad.Smith

Reputation: 1111

Powershell - Replacing a string with a variable ending with a dollar sign

I'm a bit lost with this one. For whatever reason the replace function in powershell doesn't play well with variables ending with a $ sign.

Command:

$var='A#$A#$'
$line=('$var='+"'"+"'")
$line -replace '^.+$',('$line='+"'"+$var+"'")

Expected output:

$line='A#$A#$'

Actual output:

$line='A#$A#

Upvotes: 3

Views: 2988

Answers (3)

SpellingD
SpellingD

Reputation: 2621

I don't really understand the purpose of your posted lines, it seems to me that it would just make more sense to do $line='$line='''+$var+"'", BUT if you insist on your way, just do two replace calls, like this:

$line -replace '^.+$',('$line=''LOL''') -replace 'LOL',$var

Upvotes: 0

ajk
ajk

Reputation: 4603

It looks like you're getting hit with a regex substitution that you don't want. The regex special variable $' represents everything after your match. Since your regex matches the entire string, $' is effectively empty. During the replace operation, the .Net regex engine sees $' in your expected output and substitutes in that empty string.

One way to avoid this is to replace all instances of $ in your $var string with $$:

$line -replace '^.+$',('$line='+"'"+($var.Replace('$','$$'))+"'")

You can see more information about regex substitution in .Net here:

Substitutions

Upvotes: 4

Brad.Smith
Brad.Smith

Reputation: 1111

I was able to find a band-aid of sorts by replacing $ with a special character and then reverting it back after the change. Preferably you would choose a character that doesn't have a key on your keyboard. For me I chose "¤".

$var='A#$A#$'
$var=$var -replace '\$','¤'
$line=("`$var=''")
$line -replace '^.+$',("`$line='$var'") -replace '¤','$'

Upvotes: 0

Related Questions