Rest API Authentication- Result Print Success or Failed 200/401

Welcome Forums General PowerShell Q&A Rest API Authentication- Result Print Success or Failed 200/401

Viewing 1 reply thread
  • Author
    Posts
    • #186919
      Participant
      Topics: 4
      Replies: 2
      Points: 43
      Rank: Member

      I'm trying to print Status code 200/401 in success and failed scenarios. I tried writing Power Shell Script, My script is working with status code 200. but if I want to failed my Token, `$StatusCode` is not printing 401.

      I need some suggestions for print status code in both scenarios passing one parameters.

      Here is my Script:

      try {
      if ($response = (Invoke-WebRequest @Params -ErrorAction Stop)){
      $Token = (($response.Content) | convertFrom-Json).Token
      }
      } catch [System.Net.WebException] {
      $StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) " ; $Message = " Message: $($_.Exception.Message))"
      }
      
      $StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)" "
      

      $StatusCode  is working for status code 200 only. but I want use same $Statuscode for failed status code 401.

      So, $StatusCode should works for 200 and 401 and print accordingly.

      Thanks.

       

    • #186988
      Participant
      Topics: 9
      Replies: 1277
      Points: 1,051
      Helping Hand
      Rank: Community Hero

      Getting status codes are problematic and even more so with Invoke-RestMethod. It is a common ask\complaint to get this information in the exception. Using Invoke-WebRequest, you can try this:

      https://stackoverflow.com/questions/42231486/capture-response-on-failed-401-invoke-webrequest

Viewing 1 reply thread
  • You must be logged in to reply to this topic.