Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable having a dollar sign to another variable in PowerShell?

I am using an On-Prem Server to run VSTS Build/Releases. Currently, I am trying to pass a variable from VSTS: $(password) to my script. Suppose the value of this variable $(password) is 'stringwith$sign'`

This variable $(password) needs to be injected into a string in my script:

$string = "I need to inject my password string from VSTS here "$(password)""

The String should look like this:

$string = I need to inject my password string from VSTS here "stringwith$sign"

How do I achieve this? The build/release will fail if I simply add it as $(password) since it thinks $sign in "stringwith$sign" is a variable. I cannot even use '' quotes since my variable $(password) needs to be inserted in $string.

like image 438
Nilay Avatar asked Sep 21 '25 05:09

Nilay


1 Answers

Without seeing any sample code, it's a bit hard to tell how your script works.

But basically, if you are setting a string literal that contains special characters, you can stop them from being parsed by using single quotes instead of double-quotes. For example, if you execute

$password = "stringwith$sign"
$password

Then the value of password is stringwith.

This is because powershell has parsed the string and treated $sign as being the name of a variable and has attempted to insert the value of $sign. But as $sign hasn't been declared, the default value of empty string is used.

However, if you used single quotes, i.e.

$password = 'stringwith$sign'
$password

Then the value of password is stringwith$sign.

Subsequently, setting

$string = "I need to inject my password string from VSTS here ""$password""" 

gives $string the value of

I need to inject my password string from VSTS here "stringwith$sign"

like image 171
DeanOC Avatar answered Sep 23 '25 06:09

DeanOC