ps/Modules/Alkami.PowerShell.Common/Public/Open-UrlInDefaultBrowser.ps1
2023-05-30 22:51:22 -07:00

58 lines
2.0 KiB
PowerShell

function Open-UrlInDefaultBrowser {
<#
.SYNOPSIS
Opens the Given URL in the User's Default Browser
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$url
)
$logLead = (Get-LogLeadName);
$edgeBrowserIdHash = "AppXq0fevzme2pys62n3e0fbqa7peapykr8v"
[System.Uri]$uri = $null
if (!([System.URI]::TryCreate($url, [System.UriKind]::Absolute, [ref]$uri) -and ($uri.Scheme -eq [System.Uri]::UriSchemeHttp -or $uri.Scheme -eq [System.Uri]::UriSchemeHttps))) {
Write-Warning ("$logLead : The provided URL -- {0} -- could not be parsed as an absolute URI. Be sure to pass in the URL prefix and a full URL" -f $url)
return
}
#Gets default browser from regedit; if there is none, sets to IE.HTTP; Chrome is ChromeHTML
#TODO set this up for https as well
$HKCUPath = "HKCU:\SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"
$browserIdRaw = Get-ItemPropertyValue -Name ProgId -Path $HKCUPath -ErrorAction SilentlyContinue
if(!$browserIdRaw -or $browserIdRaw -eq $edgeBrowserIdHash)
{
$browserId = "IE.HTTP"
}
else
{
$browserId = Get-ItemPropertyValue -Name ProgId -Path $HKCUPath -ErrorAction SilentlyContinue
}
try {
Write-Verbose ("$logLead : Browser ID read as {0}" -f $browserId)
New-PSDrive -PSProvider registry -Root 'HKEY_CLASSES_ROOT' -Name 'HKCR' | Out-Null
$browserCmd = (Get-Item "HKCR:\$browserId\shell\open\command" | Get-ItemProperty | Select-Object -ExpandProperty "(default)")
Write-Verbose ("$logLead : Raw browser command path read as {0}" -f $browserCmd)
if ($browserCmd -match '\".+?\"') {
return (Start-Process -FilePath $matches[0] -ArgumentList $url -PassThru).Id
}
else {
Write-Warning ("$logLead : Could not read the browser command path from the registry")
}
}
catch {
Write-Warning ("$logLead : An unexpected exception occurred while opening the URL: {0}" -f $_.Exception.Message)
}
finally {
Remove-PSDrive -Name "HKCR"
}
}