简体   繁体   中英

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:$password@org.proxy.com:80",
        "https-proxy": "http://$user:$password@org.proxy.com: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?

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`:$password@org.proxy.com:80",
        "https-proxy": "http://$user`:$password@org.proxy.com:80"
}
"@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM