如何使用JSON来Powershell Invoke-RestMethod?

时间:2018-08-02 08:43:50

标签: api powershell postman

我正在尝试使用此请求来调用API。该请求在Postman中工作正常。但是如何将其转换为PowerShell Invoke-RestMethod

这就是我尝试过的。

$token = "abcdef123456"
$url = "https://example.com/OVAV1/triggercalls/1"
$header = @{"Authorization"='abdcdef123456'}

$body =
{
"requestid": "<Echo back field>",
"templatename": "Line_Down",
"templateid": "abcde12345",
"noofrecords": 1,
"variableinfo": [
{
"<<MOBILE_NUMBER>>": "123456789",
"<<UNIQUE_CALL_IDENTIFIER>>": "A001",
"<<LinkType>>": "PRI",
"<<HostName>>": "HOSTNAME"
}
]
}

$request = Invoke-RestMethod -Uri $url -Headers $header -Body $body -ContentType "application/json" -Method Post

$request

我在Postman中尝试了JSON代码。一切正常。如何在PowerShell中使用相同的JSON代码?

1 个答案:

答案 0 :(得分:5)

您不能像这样将JSON数据放入PowerShell代码中。将其放在此处字符串中,它应该可以工作:

$body = @"
{
    "requestid": "<Echo back field>",
    "templatename": "Line_Down",
    "templateid": "abcde12345",
    "noofrecords": 1,
    "variableinfo": [
        {
            "<<MOBILE_NUMBER>>": "123456789",
            "<<UNIQUE_CALL_IDENTIFIER>>": "A001",
            "<<LinkType>>": "PRI",
            "<<HostName>>": "HOSTNAME"
        }
    ]
}
"@

您还可以将数据定义为哈希表并将其转换为JSON字符串:

$data = @{
    "requestid"    = "<Echo back field>"
    "templatename" = "Line_Down"
    "templateid"   = "abcde12345"
    "noofrecords"  = 1
    "variableinfo" = @(
        @{
            "<<MOBILE_NUMBER>>"          = "123456789"
            "<<UNIQUE_CALL_IDENTIFIER>>" = "A001"
            "<<LinkType>>"               = "PRI"
            "<<HostName>>"               = "HOSTNAME"
        }
    )
}

$body = $data | ConvertTo-Json