1

Simple enough question but I cant figure this out. I have a string with a variable name in it, and I want to replace the variable with its value. i.e.

PS > $test = "Hello `$name"
PS > $test
Hello $name
PS > $name = "Tizz"
PS > $name
Tizz

I cannot change the values of $test or $name. I need a new variable with the replaced value (I want $testTizz to have the string value "Hello Tizz"). So logically I tried this and failed

PS > $testTizz = $test -replace "`$name", $name
PS > $testTizz
Hello $name
Tizz
  • 820
  • 1
  • 15
  • 31

1 Answers1

4

Take out the backquote. Variables between double quotes will be interpreted.

$name = "Tizz"
"Hello $name"

Hello Tizz

A backquote before the $ escapes it.

"Hello `$name"

Hello $name

I don't understand why you are doing this, but this works, replacing the literal '$name', since the backquote escapes the dollarsign. Also $ is a regex expression and needs to be backslashed. %name% would be a variable in cmd, not in powershell.

$test -replace '\$name', $name

Hello Tizz
js2010
  • 23,033
  • 6
  • 64
  • 66
  • 2
    I'd give you an upvote but then you wouldn't have `9999` rep anymore.. – Paolo Jul 31 '20 at 19:12
  • Sorry, I cannot change the values of $test or $name. These are from passed in parameters. I just used this as an example. What backquote are you referring to? I want a new string variable with the replaced value. – Tizz Jul 31 '20 at 19:14
  • I updated my question. This is in a function and I am passed the $test string and cannot change. I can request that this $test variable to be "Hello %name%", then ```$test -replace "%name%", $name``` will work, but that is not the intent here. – Tizz Jul 31 '20 at 19:21
  • 1
    @Paolo Not anymore. – js2010 Jul 31 '20 at 19:29
  • 2
    @js2010 Congrats on the 10k! – Paolo Jul 31 '20 at 19:32
  • YES! Thank you! ```$test -replace '\$name', $name``` is the answer. I understand % isnt for powershell, but it would work but not what I wanted to do. – Tizz Jul 31 '20 at 19:33