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?
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.
Raw StringsThey can span multiple lines without concatenation and they don't use escaped sequences. You can use backslashes or double quotes directly.
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.
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."
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"
}
"@
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With