Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Handling for Invoke-RestMethod - Powershell

I have a powershell script using the Skytap API (REST). I would like to catch the error, if there is one, and try to display it.

For example, we are changing the IP:

Invoke-RestMethod -Uri https://cloud.skytap.com/configurations/XXXXXX/vms/YYYYYY/interfaces/ZZZZZZ?ip=10.0.0.1 -Method PUT -Headers $headers 

If the IP is used somewhere else, I will get the 409 Conflict Error (Request is well-formed but conflicts with another resource or permission).

I would like to check if the error is 409 and then tell it to do something else about it.

like image 805
user01230 Avatar asked Apr 13 '15 19:04

user01230


People also ask

What is invoke-RestMethod in PowerShell?

Description. The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.

How do I catch an error in PowerShell?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

What is the difference between invoke-RestMethod and invoke-WebRequest?

Invoke-RestMethod is perfect for quick APIs that have no special response information such as Headers or Status Codes, whereas Invoke-WebRequest gives you full access to the Response object and all the details it provides.


1 Answers

This is somewhat awkward but the only way to do it as far as I know without doing something more complicated like using .NET's WebRequest and ConvertFrom-Json (or whatever data format you are expecting).

try {     Invoke-RestMethod ... your parameters here ...  } catch {     # Dig into the exception to get the Response details.     # Note that value__ is not a typo.     Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__      Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription } 
like image 79
David Anderson Avatar answered Sep 22 '22 07:09

David Anderson