1

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%

1 Answer 1

3

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}"
Sign up to request clarification or add additional context in comments.

3 Comments

This seems to be working but it puts 'NotFound' into my variable and not 404. When I use a valid url, I get 200 in my variable. Is there a Response.StatusCodeNumber or something to that effect?
@jacekn put a + in front of $_.Exception.Response.StatusCode, then PowerShell will convert it to its underlying numerical value: try{...}catch{+$_.Exception.Response.StatusCode}
This $_.exception.response.statuscode.value__ did it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.