方法在Powershell中放入问题,问题:400格式错误的错误转换,

时间:2019-01-21 00:44:07

标签: rest powershell http-status-code-400

在Powershell中运行脚本时,Invoke-RestMethod PUT命令输出

> Invoke-RestMethod : 400 MalformedCONTENTThe data request is malformed. Required content is missing or empty.Could not acquire data. 

 + Invoke-RestMethod -Method PUT -Uri http://##.##.###.#:8022/reader/bl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

将参数(如下所述)更改为:

$headers3 = @{
Host          = "##.##.###.#"
Authorization = "Basic Jlytuwhazkfnrfhdskldmxzaaldkjgpoiudtr"
Accept        = "application/json"
}   

$body = @{
       'payload' = @{
             'sensorId'   = "ee:16:as:ea:de:963"
             'blinkCount' = 5
             'blinkOn'    = 500
             'blinkOff'   = 500
             'countPause' = 2
             'timeout'    = 5000
                    }    
}

$jso = $body | ConvertTo-Json
Invoke-RestMethod -Method PUT -Uri http://##.##.###.#:8022/reader/blink-led -Headers $headers3 -Body $jso

我多次更改了$ body参数,但仍然无法在Powerhsell中获得输出。因为我已经在Rest Client,RESTer上测试了参数,所以这些参数有效。

1 个答案:

答案 0 :(得分:0)

您正在$body定义中混合使用PowerShell和JSON表示法。

更改此:

$body = @{
    sourceName = "Anything here";
    sourceId = "Anything here ";
    sourceIP = "##.##.##.###";
    sourcePort = ####;
    datetime = "###############";
    payload = {
        monitors = [
            "REST response time",
            "Authentication failures"
        ]
    }
}

变成这两个:

$body = @{
    'sourceName' = 'Anything here'
    'sourceId'   = 'Anything here '
    'sourceIP'   = '##.##.##.###'
    'sourcePort' = ####
    'datetime'   = '###############'
    'payload'    = @{
        'monitors' = 'REST response time',
                     'Authentication failures'
    }
}

或者这个:

$body = @'
{
    "sourceName": "Anything here",
    "sourceId": "Anything here ",
    "sourceIP": "##.##.##.###",
    "sourcePort": ####,
    "datetime": "###############",
    "payload": {
        "monitors": [
            "REST response time",
            "Authentication failures"
        ]
    }
}
'@