Question:
I need to get success and/or error status code from a request using power shell. And i’m always getting a blank status.
I have tried with Invoke-WebRequest and Invoke-RestMethod.
I have sucess on the call but can’t find a way of getting the status code.
Here how is currently written:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
$resource = "some url" $Logfile = "C:/path/log.log" function LogWrite { Param([string]$logstring) Add-content $logfile -value $logstring } Try { $Response = Invoke-WebRequest -Method Post -Uri $resource Write-Output("Success.") LogWrite $Date LogWrite SuccessOnCall LogWrite $Response.StatusCode } Catch { $ErrorMessage = $_.Exception.Message Write-Output($ErrorMessage) $FailedItem = $_.Exception Write-Output($FailedItem) LogWrite $Date LogWrite ErrorOnCall LogWrite $ErrorMessage Break } |
I have also tried:
1 2 3 |
LogWrite "StatusCode:" $Response.Exception.Response.StatusCode.value__ |
I used this question (and other links) : Invoke-Restmethod: how do I get the return code?
Trying to solve this, my log does write “SuccessOnCall” but the StatusCode is blank.
Thank you.
Answer:
did you try pipe’ing with select-object ?
1 2 |
Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object StatusCode |
output
1 2 3 4 |
StatusCode ---------- 200 |
or just to get status code
1 2 |
Invoke-WebRequest -Uri apiEndpoint -UseBasicParsing | Select-Object -Expand StatusCode |
output
1 2 |
200 |
to handle unsuccessful cases,
on PowerShell v#7 + include -SkipHttpErrorCheck
parameter
or
you may need to make use of $Error
array to get most recent error and access properties accordingly.