blog

PowerShell – How to check response code from a website

There are plenty of situations where you only need one answer from a website: did it respond, and what HTTP status code did it return? That can be enough for a smoke test, a monitoring script, or a deployment check.

The original approach I used years ago relied on raw .NET web request objects. It still works, but modern PowerShell gives us a cleaner way to do the same thing while returning structured data that is easier to log or reuse.

A practical function

function Get-WebStatus {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [string[]] $Uri,

        [ValidateSet('Head', 'Get')]
        [string] $Method = 'Head',

        [ValidateRange(1, 300)]
        [int] $TimeoutSec = 15
    )

    process {
        foreach ($Item in $Uri) {
            try {
                $Response = Invoke-WebRequest -Uri $Item -Method $Method -TimeoutSec $TimeoutSec -ErrorAction Stop

                [pscustomobject] @{
                    Uri               = $Item
                    Reachable         = $true
                    StatusCode        = [int] $Response.StatusCode
                    StatusDescription = [string] $Response.StatusDescription
                    Error             = $null
                }
            } catch {
                $StatusCode = $null

                if ($_.Exception.Response -and $_.Exception.Response.StatusCode) {
                    $StatusCode = [int] $_.Exception.Response.StatusCode
                }

                [pscustomobject] @{
                    Uri               = $Item
                    Reachable         = $false
                    StatusCode        = $StatusCode
                    StatusDescription = $null
                    Error             = $_.Exception.Message
                }
            }
        }
    }
}

Get-WebStatus -Uri 'https://evotec.xyz'

Why this version is easier to use

  • It returns objects instead of writing only colored text to the console.
  • It captures the HTTP status code even when the request fails.
  • It lets you switch between HEAD and GET.
  • It is easy to export to CSV, JSON, or feed into monitoring logic.

A few practical notes

  • HEAD is usually the fastest option when you only care about the response code.
  • Some applications do not handle HEAD correctly. If that happens, rerun the check with -Method Get.
  • A non-200 result does not always mean the site is down. 301, 302, 401, and 403 can all be valid responses depending on the endpoint.

Current note

As of April 22, 2026, Microsoft documents Invoke-WebRequest as throwing a terminating error for non-success HTTP responses such as 404 and 500, which is why the try/catch pattern above is the safest way to capture both success and failure states.