Resolving URLs

by Jun 7, 2022

URLs aren’t always (directly) pointing to a resource. Often, URL act as shortcuts or static addresses that always point to latest versions. PowerShell can reveal the true URL of a resource, and you can use this for a number of cases.

Here’s an example how to resolve a shortcut link:

# this is the URL we got:
$URLRaw = 'http://go.microsoft.com/fwlink/?LinkID=135173'
# we do not allow automatic redirection and instead read the information
# returned by the webserver ourselves:
$page = Invoke-WebRequest -Uri $URLRaw -UseBasicParsing -MaximumRedirection 0 -ErrorAction Ignore
$target = $page.Headers.Location

"$URLRaw -> $target" 

And here is an example on how to resolve a product version from a static link. The latest PowerShell version can always be found using this static URL:

https://github.com/PowerShell/PowerShell/releases/latest

If you’d like to know the actual version of the latest release, try and resolve the URL:

$URLRaw = 'https://github.com/PowerShell/PowerShell/releases/latest'
# we do not allow automatic redirection and instead read the information
# returned by the webserver ourselves:
$page = Invoke-WebRequest -Uri $URLRaw -UseBasicParsing -MaximumRedirection 0 -ErrorAction Ignore
$realURL = $page.Headers.Location
$version = Split-Path -Path $realURL -Leaf 

"PowerShell 7 latest version: $version"

The same approach works for PowerShell Gallery modules as well:

# name of a module published at powershellgallery.com
$ModuleName = 'ImportExcel'

$URL = "https://www.powershellgallery.com/packages/$ModuleName"
# get full URL (including latest version):
$page = Invoke-WebRequest -Uri $URL -UseBasicParsing -MaximumRedirection 0 -ErrorAction Ignore
$realURL = $page.Headers.Location
# return version only:
$latest = Split-Path -Path $realURL -Leaf
"Module $ModuleName latest version: $latest"

Twitter This Tip! ReTweet this Tip!