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:
$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:
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.
SuccessOnCall 200 ErrorOnCall The remote server returned an error: (405) Method Not Allowed.
– CurrierWrite-Output(arg1, ...)
, useWrite-Output arg1 ...
- PowerShell cmdlets and functions are invoked like shell commands , not like methods. That is, no parentheses around the argument list, and whitespace-separated arguments (,
constructs an array as a single argument). Better yet, instead of callingWrite-Output
, use implicit output. – Ecklund$_.Exception.Response.StatusCode.value__
inside thecatch
block – Deloisedelong