Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string variable not substituted in multi-line string

Here is the code/output all in one:

PS C:\code\misc> cat .\test.ps1; echo ----; .\test.ps1
$user="arun"
$password="1234*"
$jsonStr = @"
{
        "proxy": "http://$user:[email protected]:80",
        "https-proxy": "http://$user:[email protected]:80"
}
"@
del out.txt
echo $jsonStr >> out.txt
cat out.txt
----
{
        "proxy": "http://1234*@org.proxy.com:80",
        "https-proxy": "http://1234*@org.proxy.com:80"
}

Content of string variable $user is not substituted in $jsonStr.

What is the correct way to substitute it?

like image 583
deostroll Avatar asked Feb 03 '15 05:02

deostroll


People also ask

How do I create a multi line string in PowerShell?

A multiline string is a string whose value exceeds beyond one line. In that, the string should be enclosed within a here-string(@””@). Newline or carriage return value can also be used to create a multiline string. Multiline string can also be defined by using a line break within double-quotes.

Can a string be multiple lines?

Raw StringsThey can span multiple lines without concatenation and they don't use escaped sequences. You can use backslashes or double quotes directly.

How do you pass a variable to a string in PowerShell?

PowerShell has another option that is easier. You can specify your variables directly in the strings. $message = "Hello, $first $last." The type of quotes you use around the string makes a difference.

How do I combine strings and variables in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator. $str1="My name is vignesh."


1 Answers

The colon is the scope character: $scope:$variable. PowerShell thinks you are invoking the variable $password from the scope $user. You might be able to get away with a subexpression.

$user="arun"
$password="1234*"
@"
{
        "proxy": "http://$($user):$($password)@org.proxy.com:80",
        "https-proxy": "http://$($user):$($password)@org.proxy.com:80"
}
"@

Or you could use the format operator

$user="arun"
$password="1234*"
@"
{{
        "proxy": "http://{0}:{1}@org.proxy.com:80",
        "https-proxy": "http://{0}:{1}@org.proxy.com:80"
}}
"@ -f $user, $password

Just make sure you escape curly braces when using the format operator.

You could also escape the colon with a backtick

$jsonStr = @"
{
        "proxy": "http://$user`:[email protected]:80",
        "https-proxy": "http://$user`:[email protected]:80"
}
"@
like image 135
Matt Avatar answered Oct 15 '22 02:10

Matt