There are two problems with your code:
You must use "..."
(double-quoting), i.e. an expandable string in order to get string interpolation (expansion of variable values) in your string.
By contrast, '...'
(single-quoting) is a verbatim string, so any variable references such as $SERIAL
in it are not expanded.
See the conceptual about_Quoting_Rules help topic.
Since you're trying to create a JSON string, any expanded variable values that represent JSON strings must be enclosed in embedded "
characters, which you must escape as `"
(or ""
), as all "
chars. embedded inside "..."
must be.
`
, the so-called backtick, is PowerShell's general escape character. Inside "..."
, it not only escapes "
and $
to treat them literally, but also marks the start of escape sequences such as `n
for an LF character - see about_Special_Characters.
Therefore:
$response = Invoke-WebRequest -Uri 'BLAHBLAHBLAH' -Method POST `
-Headers $headers `
-ContentType 'application/json' `
-Body "{`"archived`":false,`"warranty_months`":null,
`"depreciate`":false,
`"supplier_id`":null,
`"requestable`":false,
`"rtd_location_id`":null,
`"last_audit_date`":`"null`",
`"location_id`":null,
`"status_id`":2,
`"model_id`":34,
`"serial`":`"$SERIAL`",
`"name`":`"$COMPUTERNAME}`""
Note, however, that you can use a here-string to avoid the need for escaping the embedded "
chars:
$response = Invoke-WebRequest -Uri 'BLAHBLAHBLAH' -Method POST `
-Headers $headers `
-ContentType 'application/json' `
-Body @"
{"archived":false,"warranty_months":null,
"depreciate":false,
"supplier_id":null,
"requestable":false,
"rtd_location_id":null,
"last_audit_date":"null",
"location_id":null,
"status_id":2,
"model_id":34,
"serial":"$SERIAL",
"name":"$COMPUTERNAME}"
"@
Finally, it may be easier to construct your data as a hashtable and let PowerShell convert it to JSON for you via ConvertTo-Json
:
$response = Invoke-WebRequest -Uri 'BLAHBLAHBLAH' -Method POST `
-Headers $headers `
-ContentType 'application/json' `
-Body (
@{
archived = $false
warranty_months = $null
depreciate = $false
supplier_id = $null
requestable = $false
rtd_location_id = $null
last_audit_date = 'null'
location_id = $null
status_id = 2
model_id = 34
serial = $SERIAL
name = $COMPUTERNAME
} | ConvertTo-Json
)
Note how the hashtable keys don't need double-quoting (except if they contain special characters), and variables with string values can be used as-is (ConvertTo-Json
automatically encloses them in "..."
).