Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active November 13, 2020 18:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdhitsolutions/325ca7ffec66b71c63f473b2e1316364 to your computer and use it in GitHub Desktop.
Save jdhitsolutions/325ca7ffec66b71c63f473b2e1316364 to your computer and use it in GitHub Desktop.
PowerShell function to open a file in your default browser
#Internet Explorer may not work well with multiple files
#Edge does its own thing
Function Out-Browser {
[cmdletbinding()]
Param(
[Parameter(Position = 0, Mandatory,ValueFromPipelineByPropertyName)]
[Alias("Path")]
[string]$Fullname
)
Begin {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
Function GetBrowserCmd {
$reg = Get-item -path HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice
$ProgId = $reg.GetValue("ProgID")
if ($progid -match "^Appx\w+") {
Write-Warning "Looks like you are running Microsoft Edge"
Return ""
}
else {
(get-itemproperty -path "HKLM:\SOFTWARE\Classes\$ProgID\shell\open\command" -name "(default)").'(default)'
}
}
} #begin
Process {
$filename = (Convert-Path -path $Fullname).Replace('\','/')
$uri = "file:///$filename"
Write-Verbose "[PROCESS] Opening $uri"
$open = GetBrowserCmd
if ($open) {
$cmd = $open -replace "%1",$uri
Write-Verbose "[PROCESS] $cmd"
[regex]$rx = '^.*\.exe"'
$app = $rx.match($cmd).value
$arg = $rx.split($cmd) | where {$_}
start-process -FilePath $app -ArgumentList $arg
}
else {
Write-Verbose "[PROCESS] Opening with Microsoft Edge"
start microsoft-edge:$uri
}
}
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
}
Set-Alias -name ob -value Out-Browser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment