Check-BrokenLinks

Tired of using ‘System.Net.WebClient’ as I am? Upgrade to PowerShell v3 and use Invoke-WebRequest instead!
My first application of Invoke-WebRequest is to create a broken links checker for my website. Choose a webpage URI to scan, it will get all the links in it, and make a hit for each one.

 

<#
.SYNOPSIS
Check-BrokenLinks.ps1 - Runs a few SQL queries against an MS SQL database
.DESCRIPTION
Check-BrokenLinks.ps1 - Gets all the a href links on the specified URL and make a hit for each one to check the returned status code.
.PARAMETER URL
Defines the URL for which the links have to be checked
Mandatory parameter
No default value
.NOTES
File Name   : Check-BrokenLinks.ps1
Author      : Fabrice ZERROUKI - fabricezerrouki@hotmail.com
.EXAMPLE
PS D:\> .\Check-BrokenLinks.ps1 -URL www.zerrouki.com/about/
Gets all the a href links on the http://www.zerrouki.com/about/ page and make a hit for each one to check the returned status code.
#>
#requires -version 3.0
Param(
[Parameter(Mandatory=$true, HelpMessage="You must provide a URL to analyze.")]
$URL
)

filter ColorPattern( [string]$Pattern, [ConsoleColor]$Color, [switch]$SimpleMatch ) {
if( $SimpleMatch ) { $Pattern = [regex]::Escape( $Pattern ) }

$split = $_ -split $Pattern
$found = [regex]::Matches( $_, $Pattern, 'IgnoreCase' )
for( $i = 0; $i -lt $split.Count; ++$i ) {
Write-Host $split[$i] -NoNewline
Write-Host $found[$i] -NoNewline -ForegroundColor $Color
}
Write-Host
}
Clear-Host

$linksList=(Invoke-WebRequest –Uri $URL).Links | Where-Object {$_.href -like “http*”} | Select-Object -ExpandProperty href -Unique
$hash=@{}

ForEach($link in $linksList)
{
Try {
$status=Invoke-WebRequest –Uri $link -MaximumRedirection 0 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty StatusCode
}
Catch {
$_
$status=$_
}
$hash.Add($link,$Status)
}
$hash.GetEnumerator() | Sort Name | Format-Table @{Label="URL" ; Expression = {$_.Name}}, @{Label="Status Code" ; Expression = {$_.Value}} | Out-String | ColorPattern 200 DarkGreen

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top