jacekn
jacekn

Reputation: 1541

How to get HTTP Status Code from Powershell Invoke-WebRequest call?

I'm running a Windows .bat file trying to execute a process via url. I'd like to extract the Http Status Code from this call. The examples I've found led me to this snippet which reports 200 just fine. But when I test with invalid url to get a 404, Http Status Code isn't set. Instead, error details are being displayed in the DOS prompt. Is there a way I can reliably extract Http Status Code, regardless of the status code series? If this snippet doesn't work, I'm open to other ideas. I just need to have that status code in the variable so I can continue my logic.

SET URL=https://stackoverflow.com

For /f "usebackqdelims=" %%A in (
  `Powershell.exe -nologo -NoProfile -command "Invoke-WebRequest -Uri %URL% -UseBasicParsing | Select-Object -Expand StatusCode"`

) Do Set HTTP_STATUS_CODE=%%A

echo HTTP_STATUS_CODE=%HTTP_STATUS_CODE%

Upvotes: 1

Views: 7228

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

HTTP 404 is treated as an error, so the command never returns anything.

Wrap the pipeline in a try/catch block and grab the status code from the thrown exception instead:

Powershell.exe -nologo -NoProfile -command "try{Invoke-WebRequest -Uri %URL% -UseBasicParsing -EA Stop | Select-Object -Expand StatusCode}catch{$_.Exception.Response.StatusCode}"

Upvotes: 3

Related Questions