Out-Default URL Launcher (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/803"></script>download | new post
This bad boy is from an email by Bruce Payette—the master. Here are some notes from the email:
“Add the function below to your profile and you should have what you want. By overriding Out-Default,
this function can do a couple of things. First, it captures the last object written in
$GLOBAL:LAST. The more germane feature is that it traps any errors that are written. If the error is
“command not found” and the command takes the form of “http://msdn.microsoft.com” or “live.com” it
uses [diagnostics.process]::start() to launch the browser (this could just be start-process in V2). Finally,
if the command name resolves to a directory, it cd’s to that directory.
This works in both the console host and the ISE but the implementation depends on our host convention – that
all output and errors are routed through Out-Default, so it may not work in other hosts.” – Bruce Payette
- # Wrapper for Out-Default that saves the last object written
- # and handles missing commands if the command is a directory
- # or an URL
- #
- function Out-Default `
- {
- [CmdletBinding(ConfirmImpact="Medium")]
- param(
- [Parameter(ValueFromPipeline=$true)] `
- [System.Management.Automation.PSObject] $InputObject
- )
- begin
- {
- $wrappedCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet(
- "Out-Default")
- $sb = { & $wrappedCmdlet @PSBoundParameters }
- $__sp = $sb.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- }
- process {
- $do_process = $true
- if ($_ -is [System.Management.Automation.ErrorRecord])
- {
- if ($_.Exception -is [System.Management.Automation.CommandNotFoundException])
- {
- $__command = $_.Exception.CommandName
- if (test-path -path $__command -pathtype container)
- {
- set-location $__command
- $do_process = $false
- }
- elseif ($__command -match '^http://|\.(com|org|net|edu)$')
- {
- if ($matches[0] -ne "http://") { $__command = "HTTP://" + $__command }
- [diagnostics.process]::Start($__command)
- $do_process = $false
- }
- }
- }
- if ($do_process)
- {
- $global:LAST = $_;
- $__sp.Process($_)
- }
- }
- end { $__sp.End() }
- }
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.
PowerShell Code Repository