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 { | |
| <# | |
| .SYNOPSIS | |
| Test web request. | |
| .DESCRIPTION | |
| 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. | |
| .EXAMPLE | |
| Test-WebRequest 'google.com' | |
| This should return True. | |
| .EXAMPLE | |
| Test-WebRequest 'google.com/api' | |
| This should return False. | |
| .NOTES | |
| Author: Øyvind Kallstad | |
| Version: 1.0 | |
| Date: 20.09.2016 | |
| .OUTPUTS | |
| System.Boolean | |
| .INPUTS | |
| System.String | |
| System.Uri | |
| .LINK | |
| https://communary.net/ | |
| #> | |
| [CmdletBinding()] | |
| param ( | |
| # Specifies the Uniform Resource Identifier (URI) of the resource to test. | |
| [Parameter()] | |
| [uri] $Uri, | |
| # Specifies a user account that has permission to send the request. | |
| [Parameter()] | |
| [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. | |
| [Parameter()] | |
| [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 | |
| } | |
| } |