Author Posts

August 19, 2015 at 6:55 am

Hi,

I am trying to get the curl below translated into powershell. I am fairly sure it is the formatting of the $body but I am not having much luck at figuring it out myself.

The curl line:

curl -d '{ "auth_token":"uubiegoviogiePhohlaexei7ab2beebe", "items": [ {"label": "server1", "value": "OK"}, {"label": "server2", "value": "OK"} ] }' http://dashing.domain.tld/widgets/servers

What I have:

$proxyserver = "http://proxy.domain.tld:3128"
$auth_token = "MyAuthToken"
$dashing = "http://dashing.domain.tld/widgets/servers"

$body = @{
    auth_token = "$auth_token"
    items = @{
        label = "server1"
        value = "OK"
        label = "server2"
        value = "OK"
        }
    }

Invoke-RestMethod -Proxy $proxyserver -Uri "$dashing" -Method Post -Body (ConvertTo-Json $body)

Any help will be appreciated

Thanks

Kim

August 19, 2015 at 7:14 am

If you just look at the conversion of your hash table to json

$body = @{
auth_token = "$auth_token"
items = @{
label = "server1"
value = "OK"
label = "server2"
value = "OK"
}
}

ConvertTo-Json -InputObject $body

I got this error

At line:6 char:9
+ label = "server2"
+ ~~~~~
Duplicate keys 'label' are not allowed in hash literals.
At line:7 char:9
+ value = "OK"
+ ~~~~~
Duplicate keys 'value' are not allowed in hash literals.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DuplicateKeyInHashLiteral

In a hash table all of your keys must be unique.

The json doesn't form so your call to the web service fails

August 19, 2015 at 7:24 am

Try this to create your JSON

$items = @()
$items += @{label = "server1"; value = "OK"}
$items += @{label = "server2"; value = "OK"}

$body = New-Object -TypeName PSOBject -Property @{
auth_token = "$auth_token"
Items = $items
}

ConvertTo-Json -InputObject $body

August 19, 2015 at 7:56 am

If you need to dictate the order of properties in the JSON

$items = @()
$items += @{label = "server1"; value = "OK"}
$items += @{label = "server2"; value = "OK"}

$props = [ordered]@{
auth_token = "$auth_token"
Items = $items
}

$body = New-Object -TypeName PSOBject -Property $props

ConvertTo-Json -InputObject $body

August 19, 2015 at 8:18 am

Hi Richard,

Thanks, I will try those in the morning when I get to the office

August 19, 2015 at 10:27 pm

Hi Richard,

Thank you so much, that works like a bomb 🙂

I also needed to add -ContentType "application/json" to my invoke-RestMethod command I am now updating the dashboard as expected.