PoshCode Archive  Artifact [ca031665d8]

Artifact ca031665d8eab5448f338563802dec1ba03cc864c43ef7f3c3ac7f49629013a9:

  • File Out-Default-URL-Launcher.ps1 — part of check-in [ac353c1e73] at 2018-06-10 14:24:08 on branch trunk — This bad boy is from an email by Bruce Payette—the master. Here are some notes from the email: (user: halr9i000 size: 2690)

# encoding: ascii
# api: powershell
# title: Out-Default URL Launcher
# description: This bad boy is from an email by Bruce Payette—the master.  Here are some notes from the email:
# version: 0.1
# type: function
# author: halr9i000
# license: CC0
# x-poshcode-id: 803
# x-archived: 2016-04-19T06:39:07
# x-published: 2009-01-14T09:30:00
#
# “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() }
}