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.

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.

The Location key’s value contains the redirected URL.

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