【发布时间】:2020-02-28 06:05:58
【问题描述】:
我有以下 PowerShell 脚本,它在 Windows 10 中使用 cURL 并且运行良好:
$Body = @{
'data' = @{
'CID' = 15;
'HID' = 37;
'Type' = "TYPE1";
'downloadOn' = "NEXT_CONTACT";
'AutomationEnabled' = "True";
}
}
$CurlArgument = '-s', '-X', 'PATCH',
'-H', 'Content-Type: application/json',
$URL,
'-H',
$AuthBearer,
'-d',
(($Body | ConvertTo-Json) -replace '"', '\"')
Write-Host "$Section cURL command took" ("{0:n1}" -f (Measure-Command {$UpdateResponse = & $CURLEXE @CurlArgument}).TotalSeconds) "Seconds" -ErrorAction SilentlyContinue
我不能使用 cURL,我需要在我的生产服务器上使用本机 Invoke-WebRequest。我需要把上面的转换成一个Invoke-WebRequest命令,我已经做到了,如下:
$Body = @{
'data' = @{
'CID' = 15;
'HID' = 37;
'Type' = "TYPE1";
'downloadOn' = "NEXT_CONTACT";
'AutomationEnabled' = "True";
}
}
(($Body | ConvertTo-Json) -replace '"', '\"')
$Method = "PATCH"
$Header = @{"Accept" = "*/*" ; "Cache-Control" = "no-cache" ; "Host" = "myURL"; "accept-encoding" = "gzip,deflate"; "Authorization" = "Bearer $SessionToken" }
$ContentType = "application/json"
Write-Host "$Section Invoke-WebRequest command took" ("{0:n1}" -f (Measure-Command { $UpdateResponse = Invoke-WebRequest -Method $Method -Uri $URL -Header $Header -ContentType $ContentType -Body $Body }).TotalSeconds) "Seconds"
当我运行 Invoke-WebRequest 时,我收到以下错误,即 JSONObject 文本必须以 '{' 开头:
Invoke-WebRequest : {"status":"FAILURE","errors":...."message":{"5011":"A JSONObject text must begin with '{' at 1 [character 2 line 1]"}}]}
我的 $Body 看起来像这样,即它以 '{' 开头:
{
\"data\": {
\"downloadOn\": \"NEXT_CONTACT\",
\"HID\": 37,
\"AutomationEnabled\": \"True\",
\"CID\": 15,
\"Type\": \"TYPE1\"
}
}
我尝试使用和不使用“-replace '"', '\"'", from this post" cURL to PowerShell - Double hash table in --data?
查看我的 $Body JSON“对象”(?),我可以看到:
Name Value
---- -----
data {downloadOn, HID, AutomationEnabled, CID...}
查看我的Value,我可以看到它列出如下:
Name Value
---- -----
downloadOn NEXT_CONTACT
HID 37
AutomationEnabled True
CID 15
Type TYPE1
我想也许我应该发送值,而不是发送 -Body $Body,如下所示(也失败了),并带有相同的消息。
-Body $Body.Values
昨晚我进行了大量搜索,但不知道如何将其转换为成功的 Invoke-WebRequest,不胜感激。
【问题讨论】:
标签: json powershell