Use PowerShell’s Invoke-WebRequest to report if a website is up or down

If Internet Control Message Protocol (ICMP) — a protocol used to communicate problems with data transmission — is disabled, PowerShell’s Invoke-WebRequest can be a helpful alternative to use to monitor of a website is up or down.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# What website would you like to check if it is up or down?
$website = "https://example.com/"
 
# How many seconds do you wish to pause between attempts?
$seconds = 3
 
# Loop indefinitely
while($true) {
 
    # Clear previous result
    $response = $null
 
    # Send an HTTP request to a website and store the response object in $response
    try {
        $response = Invoke-WebRequest -Uri $website #-ErrorAction SilentlyContinue -UseBasicParsing -DisableKeepAlive
    } catch {
        $response = $null
    }
 
    # If the HTTP status code is 200 (OK), write "OK" to the console with a green background
    if($response.StatusCode -eq 200) {
        Write-Host (Get-Date).ToString() "Okay" -BackgroundColor Green
    } 
 
    # If the HTTP status code is not 200 (OK), write "Fail" to the console with a red background and play a sound
    else {
        Write-Host (Get-Date).ToString() "Failed" -BackgroundColor Red
        [System.Console]::Beep(200,1500)
    }
 
    # Wait for X seconds (defined above) before sending another request
    Start-Sleep -Seconds $seconds
}