PowerShell – Capturing a Redirected URL from a Web Request

I was recently tasked to write an automation script in PowerShell to invoke methods on a REST API.  In this case, the API redirected the web requests to a more specific URL with an HTTP/302 response.  When attempting to use POST, PUT, or any other methods besides GET, the REST API issued an HTTP/308 response and would not accept the web request.  The solution was to capture the redirected URL, which is fairly straightforward in PowerShell.

$Uri = 'http://go.microsoft.com/fwlink/?LinkId=113387'
$Results = Invoke-WebRequest -Method Get -Uri $Uri -MaximumRedirection 0 -ErrorAction SilentlyContinue

The key is to use the -MaximumRedirection parameter with a value of 0.  This prevents PowerShell from following the HTTP/302.  The result of Invoke-WebRequest is a WebResponseObject which contains a Headers property.  Inside the Headers property is a Location key with the value being the redirected URL.

$Results | Get-Member
TypeName: Microsoft.PowerShell.Commands.WebResponseObject

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseResponse Property System.Net.WebResponse BaseResponse {get;set;}
Content Property byte[] Content {get;set;}
Headers Property System.Collections.Generic.Dictionary[string,string] Headers {get;}
RawContent Property string RawContent {get;set;}
RawContentLength Property long RawContentLength {get;}
RawContentStream Property System.IO.MemoryStream RawContentStream {get;}
StatusCode Property int StatusCode {get;}
StatusDescription Property string StatusDescription {get;}

The Location key’s value contains the redirected URL.

$Results.Headers

Key Value
--- -----
Pragma no-cache
X-AspNetMvc-Version 5.2
Connection keep-alive
Content-Length 0
Cache-Control no-cache
Date Sun, 23 Oct 2016 21:03:08 GMT
Expires -1
Location http://technet.microsoft.com/library/hh849895.aspx
Server Microsoft-IIS/8.5
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET

Below is an example using an if statement to check for the HTTP/302 status code before writing the redirected URL.

if ($Results.StatusCode -eq 302) 
{
     Write-Host $Results.Headers.Location 
} 

http://technet.microsoft.com/library/hh849895.aspx

 

Jimmy McNatt
Jimmy McNatt
Articles: 38