How to insert PowerShell variables into a string block

Viewed 2289

Quick question, i'm trying to insert a variable into a string json body block like below, but when i perform a rest api call by passing the json body into the invoke-webrequest function, the variable is actually not getting inserted. In the alert software i'm using i just see the message as 'The following host $($scrapperHost) is not running!!'

 #variable
    $myHost = $Env:Computername
    #variable prints the correct hostname
    #string json body
    $jsonBody = @'
    {
        "message": "The following host $($myHost) is not running!!"}
    }
1 Answers

There are several ways you can insert variables into strings / Here Strings.

For your specific example, instead of using @' '@ you can use @" "@, and you can insert the variable without the $ at the beginning:

#variable
$myHost = $Env:Computername
#variable prints the correct hostname
#string json body
$jsonBody = @"
{
    "message": "The following host ${myHost} is not running!!"}
}
"@

This would also work fine, always using @" "@:

"message": "The following host $myHost is not running!!"

Or:

# This is very useful when you want to insert a property of your variable
"message": "The following host $($myHost) is not running!!"`

Another example:

$jsonBody = @'
{{
    "message": "The following host {0} is not running!!"
}}
'@ -f $myHost

Notice I'm using double {{ }} because you need to escape, basically you're telling Powershell you want a literal curly brace instead of using the curly brace as a special character.

There are a lot more examples you can use to insert variables into strings, check out this post by Kevin Marquette: https://powershellexplained.com/2017-01-13-powershell-variable-substitution-in-strings/

Related