6

#PSTip Retrieve a redirected URL – PowerShell 3.0 way!

Note: This tip requires PowerShell 3.0 or above.

In an earlier tip, we looked at how we can retrieve the redirected URL using a .NET class. In today’s tip, we will look at how we can simplify that process using an in-built PowerShell 3.0 cmdlet – Invoke-WebRequest.

$uri = 'http://go.microsoft.com/fwlink/?LinkID=210601'
$request = Invoke-WebRequest -Uri $uri -MaximumRedirection 0 -ErrorAction Ignore

if($request.StatusDescription -eq 'found')
{
   $request.Headers.Location
}

This is it. Much simpler than the earlier approach!

Filed in: Columns, Tips and Tricks Tags: , ,

6 Responses to "#PSTip Retrieve a redirected URL – PowerShell 3.0 way!"

  1. Very nice. You should definitely change the if() test though: what you really want to check for is whether it’s .StatusCode is a 3xx Redirect code, because “Found” isn’t the only one that this would work for (at a minimum 303, 302, 304, I think). I’d just go for:

    if($request.StatusCode -ge 300 -and $request.StatusCode -lt 400) {
    $request.Headers.Location
    }

  2. Calip says:

    I’m new to Powershell web request cmdlets.

    Is possible to use just PowerShell Invoke commands (no browsers) to login to a website that then redirects you to a page where you select (get) a link to get to the page where you want to get the information? (get, post (redirect), get, get). No other way to get to page, except from/thru redirect page…

    You guys seem to understand the redirects.

    Calip

Leave a Reply

Submit Comment

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