0

I'm writing a Powershell script that needs to poll an API method in order to see if it is available. In the event that this API were to return something in the 400's, how could I act upon it?

Consider this code:

$response = Invoke-WebRequest -uri $uri -ContentType "application/json" -Method Get

$status = $response.StatusCode
Write-Output "`nStatus code is $status."

and if the response from the server is a 400 Bad Request, Powershell behaves in an unexpected way:

Invoke-WebRequest : "Some reason for a bad request." At C:\SomePath\SomeScript.ps1:19 char:26 + $response = Invoke-WebRequest -uri $uri -ContentType "appl ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Response status code is .

Note that the status code is unavailable, primarily because $response doesn't contain anything. I need $response to be populated with the details of the response from the request so that the script can decide to do something. How can I capture that information?

Ellesedil
  • 1,576
  • 1
  • 20
  • 44

0 Answers0