Search code examples
restpowershellhttp-status-code-400

Method PUT IN Powershell, Issue: 400 Malformed Error Converting,


When running the script in Powershell, the Invoke-RestMethod PUT command outputs

> 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

Changed the parameter (as told by user below) to:

$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

I have changed the $body parameter multiple times and still couldn't get the output in Powerhsell. The parameters works since I have tested the parameter on Rest Client, RESTer.


Solution

  • You're mixing PowerShell and JSON notation in your $body definition.

    Change this:

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

    into either this:

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

    or this:

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