If you need to verify a web address, it’s natural to look into Invoke-WebRequest, capturing the results and check the StatusCode if the request was successful. There is just one problem…

If the URI is invalid, Invoke-WebRequest throws a terminating error, and no amount of -ErrorAction SilentlyContinue will stop it from doing this.

I got fed up with having to code around this so I decided to write a helper function that “fixes” this problem.

It will take a string or a URI object as input and the output is a boolean; either True or False, similar to how Test-Path works.

There is nothing fancy going on here, just working around a quirk/bug in Invoke-WebRequest, but if you find a bug, or have an idea for a new feature you would like me to add, please let me know in the comments below.

function Test-WebRequest {
Test web request.
This function can be used to test a web request to a URI. It functions similarly to Test-Path and will either return
True or False.
Test-WebRequest 'google.com'
This should return True.
Test-WebRequest 'google.com/api'
This should return False.
Author: Øyvind Kallstad
Version: 1.0
Date: 20.09.2016
param (
# Specifies the Uniform Resource Identifier (URI) of the resource to test.
[uri] $Uri,
# Specifies a user account that has permission to send the request.
[PSCredential] $Credential,
# Specifies how long the request can be pending before it times out. Enter value in seconds.
# The default value, 0, specifies an indefinite time-out.
[int32] $TimeoutSec = 0
try {
$result = Invoke-WebRequest Uri $Uri Method Head Credential $Credential TimeoutSec $TimeoutSec
catch {
$result = $null
if ($result.StatusCode -eq 200) {
Write-Output $true
else {
Write-Output $false

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s