myssa
myssa

Reputation: 23

Powershell Yammer REST API POST syntax issue

I've got kind of a newbie question regarding the correct syntax to pass a variable using Invoke-RestMethod. Here is the code :

    $Payloadjson = '{
    "body": $tickets_stats,
    "group_id" : "7837105",
    "replied_to_id": $replied_to_id
    }'

    # echo $Payloadjson
    Invoke-RestMethod -Method Post -Uri $uri_post -Header $Headers -Body $Payloadjson

The problem is that I can't get the value from $ticket_stats and $replied_to_id. I think it's because of the quote and the curly bracket.

I've tried putting a double quote before the bracket and single quote to the rest : I had the variable values but then there was an error with the Invoke-RestMethod.

If you have any idea on how to pass the variables it would be greatly appreciated.

Thanks in advance :)

Upvotes: 1

Views: 284

Answers (2)

myssa
myssa

Reputation: 23

Thanks Jisaak, looks like it's working !

On the meantime, I used another trick but your solution is more elegant :

    $Payloadjson = '{
"body": *$tickets_stats*,
"group_id" : 4783115,
"replied_to_id": *$replied_to_id*
}'

# Formatting Payload
$Payloadjson = $Payloadjson -replace '[*]',"'"

#Get value from variables
$Payloadjson = $ExecutionContext.InvokeCommand.ExpandString($Payloadjson)
$Payloadjson = $Payloadjson -replace "'",'"'

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58931

You could use a hashtable combined with the ConvertTo-Json cmdlet:

$tickets_stats = "ticket"
$replied_to_id = 123

$Payloadjson = @{
    body = $tickets_stats;
    group_id ="7837105";
    replied_to_id = $replied_to_id;
} | ConvertTo-Json

Output of $Payloadjson:

{
    "body":  "ticket",
    "replied_to_id":  123,
    "group_id":  "7837105"
}

You could also use a format string (but I would go with the hashtable):

$Payloadjson = '{
    "body": {0},
    "group_id" : "7837105",
    "replied_to_id": {1}
    }' -f $tickets_stats, $replied_to_id

Upvotes: 2

Related Questions