Command Discovery Unleashed (Part 2)

by Apr 17, 2019

When you enter a command in PowerShell, the engine triggers three events to actually discover the command you want to execute. This gives you a number of opportunities to intercept and change command discovery. Let’s teach PowerShell to send command output to Out-GridView whenever you add “>>” to a command name!

Here is the code:

$ExecutionContext.InvokeCommand.PreCommandLookupAction = {
param
(
    [string]
    $Command,

    [Management.Automation.CommandLookupEventArgs]
    $Obj
)

    # when the command ends with ">>"...
    if ($Command.EndsWith('>>'))
    {
        # ...remove the ">>" from the command...
        $RealCommand = $Command.Substring(0, $Command.Length-2)
        # ...run the original command with its original arguments,
        # and pipe the results to a grid view window
        $obj.CommandScriptBlock = {
            & $RealCommand @args | Out-GridView
            # use a new "closure" to make the $RealCommand variable available
            # inside the script block when it is later called
        }.GetNewClosure()
    }
}

Next, enter these two commands:

 
PS C:\> Get-Process -Id $PID
PS C:\> Get-Process>> -Id $PID 
 

The first command simply dumps the current process. The second command sends the results to Out-GridView automatically.

If you want to get rid of the behavior again, restart PowerShell (or assign an empty script block to the event). If you want to make the behavior permanent, add the code above to your $profile script.


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!