Check a list of urls in PowerShell to see what are valid

Recently, one of my colleagues was asked to check what of our products had images on our website and didn’t.

Being a typical developer, I didn’t like the idea of someone wasting energy on monotonous tasks like that when a machine could do it so much more accurately.

The outline of the code I used was:

$urls = @("http://www.google.com","http://www.google.com.au","http://this.doesnt.exist")

foreach($url in $urls)
{
$HTTP_Request = [System.Net.WebRequest]::Create($url)

Try
{
 $HTTP_Response = $HTTP_Request.GetResponse()
 $HTTP_Status = [int]$HTTP_Response.StatusCode
}
catch [System.Net.WebException]
{
 Write-Host "$url is invalid."
}

$HTTP_Response.Close()
}

The output for the above is: http://this.doesnt.exist is invalid.

This was a great start.
To complete this for the task at hand, I enhanced the code to populate the variable $urls with a list of all our products attached to the base image path.
This reduced the amount of time from hours to minutes to find all the missing images.

Leave a Reply

Your email address will not be published.