Adding Command Not Found Handler

by Oct 22, 2015

Whenever PowerShell comes across a command name that it does not know, you see a red error message.

However, starting with PowerShell 3.0, there is a "CommandNotFoundHandler" that you can program. It can then log things, or try and resolve the issue.

Here is a simple example. Once you run this code, whenever there is a command that PowerShell does not know, it runs Show-Command and opens a helper tool with all valid commands:

$ExecutionContext.InvokeCommand.CommandNotFoundAction =
{
  param(
    [string]
    $commandName,

    [System.Management.Automation.CommandLookupEventArgs]
    $eventArgs
  )

  Write-Warning "Command $commandName was not found. Opening LookilookiTool."
  $eventArgs.CommandScriptBlock = { Show-Command }

}

Twitter This Tip! ReTweet this Tip!