public/Get-RedirectedUri.ps1
function Get-RedirectedUri { <# .SYNOPSIS Gets the real download URL from the redirection. .DESCRIPTION Used to get the real URL for downloading a file, this will not work if downloading the file directly. .EXAMPLE Get-RedirectedURI -URI "https://download.mozilla.org/?product=firefox-latest&os=win&lang=en-US" .PARAMETER URL URL for the redirected URL to be un-obfuscated .NOTES Code from: Redone per issue #2896 in core https://github.com/PowerShell/PowerShell/issues/2896 #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$Uri ) process { do { try { $request = Invoke-WebRequest -Method Head -Uri $Uri if ($null -ne $request.BaseResponse.ResponseUri) { # This is for Powershell 5 $redirectUri = $request.BaseResponse.ResponseUri.AbsoluteUri } elseif ($null -ne $request.BaseResponse.RequestMessage.RequestUri) { # This is for Powershell core $redirectUri = $request.BaseResponse.RequestMessage.RequestUri.AbsoluteUri } $retry = $false } catch { if (($_.Exception.GetType() -match "HttpResponseException") -and ($_.Exception -match "302")) { $Uri = $_.Exception.Response.Headers.Location.AbsoluteUri $retry = $true } else { throw $_ } } } while ($retry) $redirectUri } } |