17

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?

1 Answer 1

33

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"
}
"@
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.