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!!"}
}
There are several ways you can insert variables into strings or Here-Strings. See about Quoting Rules for related information.
For your specific example, variables are expanded in double-quotes so instead of using @'...'@ you can use @"..."@:
$myHost = $env:COMPUTERNAME
$jsonBody = @"
{
"message": "The following host $myHost is not running!!"
}
"@
Another way to do it is with format string or format operator -f, notice in this case, because the string contains { and } you must escape them with a consecutive curly brace:
$jsonBody = @'
{{
"message": "The following host {0} is not running!!"
}}
'@ -f $myHost
Taking a step back, the correct way to do create your Json string would be to use ConvertTo-Json:
$jsonBody = [pscustomobject]@{
message = "The following host $myHost is not running!!"
} | ConvertTo-Json
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