resolve-uri.ps1

<#PSScriptInfo
.VERSION 1.1
.GUID 52a3719b-0d47-402e-a538-9a1623be12f2
.AUTHOR Lee Holmes
.DESCRIPTION Resolve a URI to the URIs it redirects to
#>


<#
.Synopsis
   Resolve a URI to the URIs it redirects to
.EXAMPLE
   PS> Resolve-Uri https://bitly.is/1g3AhR6
    
   https://bitly.is/1g3AhR6
   https://bitly.com/
#>

param(
    ## The URI to resolve
    [Parameter(Mandatory, Position = 0)]
    $Uri
)

$ProgressPreference = "Ignore"
$ErrorActionPreference = "Stop"

while($Uri)
{
    $Uri

    $wc = [System.Net.HttpWebRequest]::Create($Uri)
    $wc.AllowAutoRedirect = $false

    try
    {
        $response = $wc.GetResponse()

        if($response.Headers["Location"])
        {
            $Uri = $response.Headers["Location"]
        }
        else
        {
            $Uri = $null    
        }           
    }
    catch
    {
        if($_.Exception.InnerException.Response.StatusCode -eq "Moved")
        {
            $Uri = $_.Exception.InnerException.Response.Headers["Location"]
        }
        else
        {
            throw $_
        }
    }
}