Friday fun: follow URI redirects

Lee Holmes twitted recently the following:

It’s available on the PowerShell gallery: resolve-uri.ps1

It appears that I wrote another script to achieve the same because of VSCode that introduced another redirect back in November.
Mine looks like this:

Function Get-URINewLocation {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[system.URI]$URI
)
Begin {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}
Process {
$HT = @{
URI = $URI
UseBasicParsing = [switch]::Present
MaximumRedirection = 0
ErrorAction = 'SilentlyContinue'
}
$r = (Invoke-WebRequest @HT -Verbose:$false)
Write-Verbose -Message "Testing URI: $($URI)"
if ($r.StatusCode -eq 301) {
Write-Verbose -Message "New permanent location found $($r.Headers.Location)"
Get-URINewLocation -URI "$($r.Headers.Location)"
} elseif ($r.StatusCode -eq 302 -and $r.StatusDescription -eq 'Moved Temporarily') {
Write-Verbose -Message "New temp location found $($r.Headers.Location)"
Get-URINewLocation -URI "$($r.Headers.Location)"
} elseif ($r.StatusCode -eq 302 -and $r.StatusDescription -eq 'Found') {
$($r.Headers.Location)
} else {
Write-Warning -Message "Error code is $($r.StatusCode)"
}
}
End {}
}
Get-URINewLocation -URI 'https://go.microsoft.com/fwlink/?linkid=850641' -Verbose

  • What are the differences between the 2 approaches?
    • Mine sends back only a single string in the output stream while his solution sends all the URI used and being redirected:

    • Mine uses a recursive approach and his approach uses a while loop.
    • Mine shows in the verbose stream what kind of redirect happened, if it’s a temporary redirect or if it’s permanent.

    As usual, there are always more than one way to skin a cat 😀

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 )

Google photo

You are commenting using your Google 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

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