Search code examples
powershellvariablespowershell-4.0

Place Variable value inside "" in Powershell


I am writing a small script in powershell and want to build a variable in a particular format.

$name="abc"
$json = '{\"name\":\"$name\",\"projectId\":\"10034\"}'
$json

when I am printing the value the value appears to be -

{\"name\":\"$name\",\"projectId\":\"10034\"}

I want to the output to be -

{\"name\":\"abc\",\"projectId\":\"10034\"}

How can we place the variable value inside ""(double quotes) in this case.


Solution

  • If you want string interpolation, you have to use double quotes. For using double quotes inside double quotes , you have to escape them with `(backquote).

    $name="abc"
    $json = "{\`"name\`":\`"$name\`",\`"projectId\`":\`"10034\`"}"
    $json
    

    The output is:

    {\"name\":\"abc\",\"projectId\":\"10034\"}