Skip to content

Instantly share code, notes, and snippets.

@thom-s
Last active July 26, 2022 12:22
Show Gist options
  • Save thom-s/8fd71f548164c01f25226ba0aca2cb7c to your computer and use it in GitHub Desktop.
Save thom-s/8fd71f548164c01f25226ba0aca2cb7c to your computer and use it in GitHub Desktop.
Return Web Request Status Code as Integer (PowerShell Core 6)
$uri = "https://httpstat.us/404" # Replace '404' by any status code you want to test
try {
$r = Invoke-WebRequest -URI $uri -SkipCertificateCheck -MaximumRedirection 0
$a = [int]$r.StatusCode
}
catch {
$a = [int]$_.Exception.Response.StatusCode
}
write-output $a
@thom-s
Copy link
Author

thom-s commented Jan 29, 2019

Invoke-WebRequest returns an error for all 3xx, 4xx and 5xx HTTP status codes, this can make it difficult to analyse HTTP status codes with PowerShell. This code will always return the status code as an integer, even if an error occurs.

Currently, this only works in PowerShell Core 6 due to the -SkipCertificateCheck parameter.
You can remove -MaximumRedirection depending on your needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment