getting return code from Invoke-RestMethod

Welcome Forums General PowerShell Q&A getting return code from Invoke-RestMethod

This topic contains 4 replies, has 4 voices, and was last updated by

 
Moderator
2 weeks, 5 days ago.

  • Author
    Posts
  • #126642

    Participant
    Points: 15
    Rank: Member

    Is there a way to get a return code (i.e., 200, 404, etc.) from Invoke-RestMethod?  I am getting the response string but I would like the numeric return code from the REST call as well.  Thanks.

  • #126743

    Participant
    Points: 889
    Helping Hand
    Rank: Major Contributor

    Please use Invoke-WebRequest...

  • #126777

    Participant
    Points: 15
    Rank: Member

    With Invoke-WebRequest, this can be done.  The details are that if you assign the return value from the cmdlet to $Response, the return code of the web call is $Response.StatusCode while the main content is $Response.Content.  Thank you.

  • #126785

    Participant
    Points: 52
    Rank: Member

    In PowerShell 6, Invoke-RestMethod has a "ReponseHeadersVariable" parameter for this. Unfortunately, it isn't available in 5.1 and earlier, so the workaround as already mentioned is to use Invoke-WebRequest.

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-6

  • #126921

    Moderator
    Points: 175
    Team MemberHelping Hand
    Rank: Participant

    Had no idea about the ReponseHeadersVariable!  Great tip John!

You must be logged in to reply to this topic.