gaurav sharma
gaurav sharma

Reputation: 133

Need to get a value in single quotes in the body section while calling a restapi through powershell

I'm using below script to call a RestAPi using powershell:

$cd = 12000
$Url = 'https://exampleSet/Set'
$Body = @{
    OperationType = 'new'
    Number = "'$($cd)'"
    CdAspId = 'Z_CK_BUGFIX'
    CdType = 'CA_106_4'
} | ConvertTo-Json

$headers = @{
'ContentType' = 'application/json'
'Accept' = 'application/json'
'APIKey' = 'abcdef'
}
Invoke-RestMethod -contentType "application/json" -Uri $url -Method Post -body $Body -Headers $headers

While execution, powershell task in Azure is showing me internal server error. I need help in passing the value in the body as:

Number = '12000'

How can I get the values in body in single quotes. Please help in this.

Upvotes: 1

Views: 59

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174525

As mentioned in the comments, JSON exclusively uses double-quoted string literals, so trying to create a JSON document with a property entry Number = '12000' doesn't make any sense - it wouldn't be valid JSON.

To force string encoding rather than a numerical value, simply surround the value with double-quotes in PowerShell:

$Body = @{
    OperationType = 'new'
    Number = "$cd"
    CdAspId = 'Z_CK_BUGFIX'
    CdType = 'CA_106_4'
} | ConvertTo-Json

Upvotes: 3

Related Questions