Kyle Gibbons Kyle Gibbons - 1 year ago 148
reST (reStructuredText) Question

PowerShell Invoke-RestMethod PUT causes newlines in the console

I am using a PowerShell module to interact with a manufacturer's REST API. The module is written by the manufacturer and makes use of the Invoke-RestMethod built in function.

I noticed when running my program with few outputs turned on that I was getting a ton of lines appearing in the console. I had never seen that before, so i decided to dig in. I traced the issue down to a single line of code:

Invoke-RestMethod -Headers $session.DirectoryAuthHeader -Uri $uri -Method $Method -Body $Body

I further instrumented it bu outputting to the console all of the variables that are being sent to the function. This issue only seems to happen when Invoke-RestMethod is using the PUT method. GET and POST do not yield any new lines. I took a look at the transactions in Fiddler and the only thing that jumped out at me was the PUT method returned a blank body.

Any ideas? I'm hoping this is just an issue with the way Invoke-RestMethod is being called and not the method itself. Thanks.

Answer Source

I ended up solving the issue myself. I'm still not 100% why PowerShell is functioning this way, but basically the blank return value (because there is no body in the response) is getting echoed to the command line. I fixed the issue by checking if the body was empty, and if not returning null instead of an empty PSObject which I believe is what was happening.

$RESTResponse = Invoke-RestMethod -Headers $session.DirectoryAuthHeader -Uri $uri -Method $Method -Body $Body

if ($RESTResponse -ne "") {
    return $RESTResponse
} else {

As I've done some more learning in PowerShell I found out what this is happening and wanted to share it for anyone else who comes across this problem.

In PowerShell there is a concept called the pipeline. Basically what happens is if cmdlets are called in succession using the pipeline character "|", the output from the preceding function becomes the input of the next function and so on. If there is output on the pipeline that isn't handled (e.g. putting it in a variable) it will eventually be echoed to the host.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download