Resolving URLs

by Jun 10, 2019

Often, URLs redirect to the final URL, so if you’d like to know where a given URL really points to, use a function like this:

function Resolve-Url
{
  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory)]
    [string]
    $url
  )
  
  $request = [System.Net.WebRequest]::Create($url)
  $request.AllowAutoRedirect=$false
  $response = $request.GetResponse()
  $url = $response.GetResponseHeader("Location")
  $response.Close()
  $response.Dispose()
  
  return $url
}

For example, the latest PowerShell release is always available via this url: https://github.com/PowerShell/PowerShell/releases/latest

By resolving this URL, you get back the currently active latest URL which in turn is a quick way of finding the latest PowerShell version available:

 
PS C:\> Resolve-Url -url https://github.com/PowerShell/PowerShell/releases/latest
https://github.com/PowerShell/PowerShell/releases/tag/v6.2.1

PS C:\> ((Resolve-Url -url https://github.com/PowerShell/PowerShell/releases/latest) -split '/')[-1]
v6.2.1

PS C:\> [version](((Resolve-Url -url https://github.com/PowerShell/PowerShell/releases/latest) -split '/')[-1] -replace 'v')

Major  Minor  Build  Revision
-----  -----  -----  --------
6      2      1      -1  
 

Twitter This Tip! ReTweet this Tip!