Contents

Powershell Clickable Hyperlinks

Contents
Updated on 2021-08-26

Having found that the Windows Terminal has gained support for the ANSI Escape sequence documented in the Hyperlinks in Terminal Emulators GIST I wrote a nice and simple PowerShell function to output these hyperlinks without having to remember the escape sequences yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function Format-Hyperlink {
  param(
    [Parameter(ValueFromPipeline = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [Uri] $Uri,

    [Parameter(Mandatory=$false, Position = 1)]
    [string] $Label
  )

  if (($PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows) -and -not $Env:WT_SESSION) {
    # Fallback for Windows users not inside Windows Terminal
    if ($Label) {
      return "$Label ($Uri)"
    }
    return "$Uri"
  }

  if ($Label) {
    return "`e]8;;$Uri`e\$Label`e]8;;`e\"
  }

  return "$Uri"
}

You can use this like so:

1
2
3
4
5
"https://example.com" | Format-Hyperlink -Label "Example Website"

# or

Format-Hyperlink -Uri "https://example.com" -Label "Example Website"

If you forget to add a Label then the function will simply print the URL directly, without the formatting sequences.

You can also use this as part of a Write-Output line:

1
Write-Output "`n`n`nPlease visit the $(Format-Hyperlink -Uri "https://example.com" -Label "Example Website")!`n`n`n"

Screenshot showing the output of the Write-Output powershell command

This should also work in PowerShell on macOS and Linux, too. (Note that it requires PowerShell 7+ for the escape sequences to be sent correctly)