Last active
July 26, 2022 12:22
-
-
Save thom-s/8fd71f548164c01f25226ba0aca2cb7c to your computer and use it in GitHub Desktop.
Return Web Request Status Code as Integer (PowerShell Core 6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Invoke-WebRequest returns an error for all
3xx
,4xx
and5xx
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.