2

#PSTip Retrieve a redirected URL

When you look at online documentation for resources and downloadable content, you will often find URLs that redirect you to another place. Most of the web masters prefer this way because the front end redirection URL can be redirected to a right location when there are updates to the content.

There are quite a few examples. To quote a couple of them:

1. SharePoint Server prerequisite software download links. We cannot use these URLs directly with cmdlets such as Start-BitsTransfer. We need to find the right redirected URL for the actual file download.

2. PowerShell 3.0 help content links

Get-Module -Name Microsoft.PowerShell.Management | select -exp HelpInfoUri

Now, taking the second example as a use case, let us see how we can retrieve the redirected URL. We can use the System.Net.WebRequest .NET class to achieve this.

Function Get-RedirectedUrl {

    Param (
        [Parameter(Mandatory=$true)]
        [String]$URL
    )

    $request = [System.Net.WebRequest]::Create($url)
    $request.AllowAutoRedirect=$false
    $response=$request.GetResponse()

    If ($response.StatusCode -eq "Found")
    {
        $response.GetResponseHeader("Location")
    }
}

In the above function, we are setting $request.AllowAutoRedirect to $false to ensure that we don’t necessarily reach the redirected URL. Our goal is to find the redirection and not really access the redirected URL. Once we set this property, if the given URL redirects to a new location, the “location” header contains the redirected URL.

PS C:\> Get-RedirectedUrl -URL 'http://go.microsoft.com/fwlink/?LinkID=210601'
http://download.microsoft.com/download/3/4/C/34C6B4B6-63FC-46BE-9073-FC75EAD5A136/
Filed in: Columns, Tips and Tricks Tags: , ,

2 Responses to "#PSTip Retrieve a redirected URL"

  1. Roy says:

    Here’s a variation and a fix to your example:

    1. The “fix” is that you have to call $response.close() – otherwise subsequent requests will time out.

    2. The variation is that the function below actually does return the redirected URL

    Thanks Ravikanth for this post – came in very handy!!

    Function Get-RedirectedUrl {
    Param (
    [Parameter(Mandatory=$true)]
    [String]$url
    )

    $request = [System.Net.WebRequest]::Create($url)
    $request.AllowAutoRedirect=$true

    try{
    $response=$request.GetResponse()
    $response.ResponseUri.AbsoluteUri
    $response.Close()
    }

    catch{
    “ERROR: $_”
    }

    }

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: