resolve-uri.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<#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 $_
        }
    }
}