October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

How to Build a Website Monitoring Script in PowerShell (with Alerts, Content Checks, and Logging)

A complete PowerShell website monitoring script that checks status codes and page text, records failures and timing, avoids alert noise, and runs on PowerShell 7.4 or Windows PowerShell 5.1.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Invoke-WebRequest in a scheduled PowerShell script, give every target explicit timeout and content rules, and treat each request as a recorded result. The pattern below checks HTTP status, optional page text, timing and exceptions without letting one failed site stop the rest. It works in PowerShell 7.4 and can be adapted to Windows PowerShell 5.1.

What the monitor should decide

A useful check answers more than “did TCP connect?” For each URL, define:

  • the URL and expected HTTP status (normally 200);
  • optional text that must appear in the response;
  • connection and response-reading time limits;
  • redirect policy and a deliberate user agent;
  • how many consecutive failures trigger an alert.

Keep the execution location in mind. A script running on one workstation or server sees the site from that network, DNS resolver and firewall. It cannot prove that users in another region have the same result.

PowerShell version and timeout parameters

Environment HTTP cmdlet Timeout parameters Important note
PowerShell 7.4 Invoke-WebRequest -ConnectionTimeoutSeconds and -OperationTimeoutSeconds Use separate limits for connection setup and reading the response.
Windows PowerShell 5.1 Invoke-WebRequest -TimeoutSec DNS resolution can take up to 15 seconds, so a very small timeout may still take 15 seconds or more to fail.

Microsoft documents Invoke-WebRequest as the cmdlet for HTTP and HTTPS requests. In PowerShell 7.4, a finite connection timeout prevents a stalled handshake from hanging indefinitely, while an operation timeout limits pauses while data is read. Windows PowerShell 5.1’s -TimeoutSec covers the older behavior and defaults to zero (no timeout), so always set it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
  • Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM)
  • Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
  • CanaKit Premium High-Gloss Raspberry Pi 4 Case with Integrated Fan Mount, CanaKit Low Noise Bearing System Fan
  • CanaKit 3.5A USB-C Raspberry Pi 4 Power Supply (US Plug) with Noise Filter, Set of Heat Sinks, Display Cable - 6 foot (Supports up to 4K60p)
  • CanaKit USB-C PiSwitch (On/Off Power Switch for Raspberry Pi 4)

Build a PowerShell 7.4 monitor

1. Define targets as data

Using objects keeps URLs and assertions separate from the checking logic. A null ExpectedText means that this target needs only an HTTP-status check.

$targets = @(
    [pscustomobject]@{
        Name          = 'Public home page'
        Url           = 'https://example.com/'
        ExpectedStatus = 200
        ExpectedText  = $null
    },
    [pscustomobject]@{
        Name          = 'Store'
        Url           = 'https://example.com/store'
        ExpectedStatus = 200
        ExpectedText  = 'Add to cart'
    }
)

Use a distinctive, stable phrase for a content assertion. Avoid text that changes on every request, such as a timestamp, rotating ad, cookie count or personalized greeting.

2. Run each request and capture a structured result

Save this as website-monitor.ps1. The try/catch is essential: with -ErrorAction Stop, non-success responses such as 404 and 500 can become terminating errors. Their status is often available on the exception response and is extracted before the error is logged.

$targets = @(
    [pscustomobject]@{ Url = 'https://example.com'; ExpectedStatus = 200; ExpectedText = $null }
)

$results = foreach ($target in $targets) {
    $started = [Diagnostics.Stopwatch]::StartNew()
    try {
        $response = Invoke-WebRequest -Uri $target.Url `
            -ConnectionTimeoutSeconds 15 `
            -OperationTimeoutSeconds 30 `
            -MaximumRedirection 5 `
            -UserAgent 'SiteMonitor/1.0' `
            -ErrorAction Stop

        $contentOk = if ($target.ExpectedText) {
            $response.Content -like "*$($target.ExpectedText)*"
        } else { $true }

        [pscustomobject]@{
            TimestampUtc = [DateTime]::UtcNow.ToString('o')
            Url          = $target.Url
            StatusCode   = [int]$response.StatusCode
            ElapsedMs    = [math]::Round($started.Elapsed.TotalMilliseconds, 1)
            ResponseLength = if ($null -ne $response.Content) { $response.Content.Length } else { $null }
            ContentOk    = $contentOk
            Healthy      = ([int]$response.StatusCode -eq $target.ExpectedStatus -and $contentOk)
            Error        = $null
        }
    }
    catch {
        $status = $null
        if ($_.Exception.Response) {
            try { $status = [int]$_.Exception.Response.StatusCode } catch { }
        }
        [pscustomobject]@{
            TimestampUtc = [DateTime]::UtcNow.ToString('o')
            Url          = $target.Url
            StatusCode   = $status
            ElapsedMs    = [math]::Round($started.Elapsed.TotalMilliseconds, 1)
            ResponseLength = $null
            ContentOk    = $false
            Healthy      = $false
            Error        = $_.Exception.Message
        }
    }
}

$results | Export-Csv -Path './website-monitor.csv' -NoTypeInformation -Append

The loop emits one object per target even when a request fails. That means DNS errors, TLS failures, refused connections, timeouts and HTTP errors are recorded instead of terminating the whole run. TimestampUtc avoids ambiguity when daylight-saving rules change.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Distinguish failure classes

A status code alone is not enough for diagnosis. Add a classification field if you route alerts to a ticketing system:

  • HTTP: a response arrived with an unexpected status, such as 404 or 500.
  • Content: the status was acceptable but the expected phrase was absent.
  • DNS: the hostname could not be resolved.
  • TLS: certificate negotiation or protocol validation failed.
  • Connection: the host refused or dropped the connection.
  • Timeout: connection setup or response reading exceeded its limit.
  • Redirect policy: the redirect chain exceeded -MaximumRedirection or was otherwise rejected.

For richer classification, inspect $_.Exception.GetType().FullName and the message in catch, then map known exception types to your own labels. Keep the original message as well; it is often the fastest clue during an incident.

Rank #2
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
  • Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • Mega Heat Sink - Black Anodized

Make alerts reliable instead of noisy

Require consecutive failures

One failed request can be a transient packet loss, deploy or DNS hiccup. Maintain a small state file (JSON, CSV or a database row) keyed by URL. Increment a failure counter on an unhealthy result and reset it on success. Notify only when the counter reaches your policy, such as two consecutive failures; send a recovery notification when a previously alerting target becomes healthy.

Include actionable context

An alert should contain the URL, UTC time, failure class, status (if any), elapsed milliseconds, exception text and the last successful check. For a content failure, include the expected phrase, not the entire page. Do not put cookies, authorization headers or response bodies containing personal data into email or chat.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a scheduler

  • Windows Task Scheduler: create a task that runs pwsh.exe -NoProfile -File C:Monitorswebsite-monitor.ps1 (PowerShell 7) at a fixed interval. Configure “Run whether user is logged on or not” and a service account with permission to write the log directory.
  • Windows PowerShell 5.1: use powershell.exe instead of pwsh.exe.
  • cron or an automation runner: invoke pwsh -NoProfile -File /opt/monitors/website-monitor.ps1; use the runner’s secret store for credentials and its native retry/notification features where appropriate.

Keep structured CSV or JSON history long enough to see recurring slowdowns. Rotate files or set a retention limit so a frequently scheduled task cannot fill the disk.

Windows PowerShell 5.1 adjustments

Replace the PowerShell 7.4 timeout parameters with a single -TimeoutSec value:

$response = Invoke-WebRequest -Uri $target.Url `
    -TimeoutSec 30 `
    -MaximumRedirection 5 `
    -UserAgent 'SiteMonitor/1.0' `
    -UseBasicParsing `
    -ErrorAction Stop

Microsoft Support describes a December 9, 2025 security change that warns about script-execution risk when Windows PowerShell 5.1 parses web content. If your script only fetches content and does not require advanced DOM parsing, add -UseBasicParsing on affected systems. Test the script under the exact Windows PowerShell build that will run it.

The DNS caveat still applies: a timeout below 15 seconds may not produce an exception until DNS resolution has had time to finish. Set a realistic value and alert on repeated failures rather than trying to make the timeout as small as possible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
CanaKit Raspberry Pi 3 B+ (B Plus) Starter Kit (32 GB EVO+ Edition, Premium Black Case)
  • Includes Made in UK Raspberry Pi 3 B+ (B Plus) with 1.4 GHz 64-bit Quad-Core Processor, 1 GB RAM
  • Dual Band 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac Wireless LAN, Enhanced Ethernet Performance
  • Includes 32 GB EVO+ Micro SD Card (Class 10) Pre-loaded with OS, USB MicroSD Card Reader
  • CanaKit 2.5A USB Power Supply with Micro USB Cable and Noise Filter - Specially designed for the Raspberry Pi 3 B+ (UL Listed)
  • Premium Raspberry Pi 3 B+ Case, Display Cable, 2 x Heat Sinks, GPIO Quick Reference Card, CanaKit Full Color Quick-Start Guide

Credentials, headers and redirects

Most public health checks need no credentials. For protected endpoints, load secrets from the operating system’s secret store or the scheduler’s encrypted variables; never commit them to the script or CSV. Supply only the headers and cookies required by the endpoint, and redact them from diagnostic output.

Use a deliberate user agent so your access logs identify the monitor. Keep the default TLS negotiation unless a documented compliance requirement or endpoint-compatibility problem requires -SslProtocol; restricting protocols unnecessarily can make a healthy endpoint appear down. Limit redirects with -MaximumRedirection and investigate unexpected cross-host redirects rather than silently following an unbounded chain.

Performance and reliability considerations

  • Run checks sequentially for a small list. For dozens or hundreds of URLs, batch work carefully with PowerShell jobs or run several worker processes while respecting the sites’ rate limits.
  • Choose operation timeouts long enough for normal pages, including slow backends, but short enough to release a worker during an outage.
  • Monitor a lightweight health endpoint when one exists; downloading a multi-megabyte page every minute adds unnecessary load.
  • Record response length and elapsed time to identify regressions without treating every slower response as an outage.
  • Run from more than one network location when regional reachability matters; a single local script cannot provide independent vantage points.

Troubleshooting checklist

The script hangs

Confirm that finite timeout parameters are present for the PowerShell version in use. In 5.1, verify -TimeoutSec; remember that DNS can consume up to 15 seconds before the timeout surfaces.

A 404 or 500 stops processing

Ensure -ErrorAction Stop is set and that the request is inside try/catch. Read $_.Exception.Response.StatusCode when available and continue emitting a result for the next target.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HTTPS fails but a browser works

Compare the machine’s clock, certificate trust store, proxy settings and DNS path. Do not immediately force an older TLS protocol with -SslProtocol; use that option only for a documented compatibility or compliance reason.

The status is 200 but the check is unhealthy

Inspect the content assertion. The site may have served a login page, maintenance page, bot challenge or a redesigned phrase. Choose a stable marker and log whether ContentOk was false.

Rank #4
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (4GB RAM)
  • Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (4GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • CanaKit Mega Heat Sink - Black Anodized

PowerShell 5.1 shows a parsing-security warning

For content-only checks on systems affected by the December 9, 2025 update, add -UseBasicParsing. If you need parsed DOM features, review the warning and test the script under your organization’s security policy.

Alerts arrive for brief blips

Implement the consecutive-failure and recovery state described above. Include the last successful timestamp so responders can distinguish a one-off failure from a sustained outage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your monitor also needs a clean visual capture—for example, to verify what a customer sees after a deployment—ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP tools—take_screenshot, get_page_info and capture_pdf—let Claude, Cursor or another MCP client perform captures.

One GET request returns PNG, JPEG, WebP or PDF. The complete API reference is at https://screenshotneo.com/docs/.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Every plan includes its features, such as full-page and element captures, device presets, custom CSS or JavaScript, waits, request blocking, cookies and headers, PDF controls, signed links, asynchronous webhooks, bulk capture (100 URLs per call), caching with a chosen TTL and a usage API. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

FAQ

Can I monitor a page that requires JavaScript?

Invoke-WebRequest retrieves the HTTP response; it does not provide a full browser-rendering assertion. Use a server-side health endpoint where possible, or pair the status monitor with a rendered capture service for visual verification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should every 200 response be considered healthy?

No. A login, maintenance or bot-challenge page can return 200. Add a stable expected-text assertion for endpoints where HTTP status alone is insufficient.

Best Value
Freenove Ultimate Starter Kit for Raspberry Pi 5 4 Zero 2 W (NOT Included)
  • 5 sets of code: Python (compatible with 2&3), C, Java, Scratch and Processing (Scratch and Processing code provide graphical interfaces)
  • Detailed tutorial: Can be downloaded (in English, 962-page in total) or viewed online (original in English, can be translated into other languages by browsers) (The tutorial link can be found on the product box, no paper tutorial)
  • 128 projects from simple to complex: Provides step-by-step guide with electronics and components knowledge, each project has schematics, wiring diagrams, complete code and detailed explanations
  • 223 items in total: This ultimate kit includes the most commonly used electronic components, modules, sensors, wires and other compatible items
  • Compatible models: Raspberry Pi 5 / 500 / 400 / 4B / 3B+ / 3B / 3A+ / 2B / 1B+ / 1A+ / Zero 2 W / Zero W / Zero (NOT included in this kit)

How often should the task run?

Choose an interval that matches the incident-detection objective and the site’s acceptable request rate. A shorter interval increases detection speed, request volume and log growth; validate the schedule against your service owner’s limits.

Where should historical results live?

CSV is adequate for a small installation and easy to inspect. Use JSON or a database when you need indexed queries, retention policies, dashboards or multiple monitor workers.

Frequently Asked Questions

Can I monitor a page that requires JavaScript?

Invoke-WebRequest retrieves the HTTP response; it does not provide a full browser-rendering assertion. Use a server-side health endpoint where possible, or pair the status monitor with a rendered capture service for visual verification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should every 200 response be considered healthy?

No. A login, maintenance or bot-challenge page can return 200. Add a stable expected-text assertion for endpoints where HTTP status alone is insufficient.

How often should the task run?

Choose an interval that matches the incident-detection objective and the site’s acceptable request rate. A shorter interval increases detection speed, request volume and log growth; validate the schedule against your service owner’s limits.

Where should historical results live?

CSV is adequate for a small installation and easy to inspect. Use JSON or a database when you need indexed queries, retention policies, dashboards or multiple monitor workers.

Quick Recap

Bestseller No. 1
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM); Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
$159.99
Bestseller No. 2
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$259.95
Bestseller No. 3
CanaKit Raspberry Pi 3 B+ (B Plus) Starter Kit (32 GB EVO+ Edition, Premium Black Case)
CanaKit Raspberry Pi 3 B+ (B Plus) Starter Kit (32 GB EVO+ Edition, Premium Black Case)
Dual Band 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac Wireless LAN, Enhanced Ethernet Performance
$109.99
Bestseller No. 4
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (4GB RAM)
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (4GB RAM)
Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (4GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$209.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.