Custom Action for Unknown Commands

by Jan 17, 2023

Whenever you enter a command name that cannot be found by PowerShell, it can extend the command search by custom actions that you define.

Here is a quick and fun example that illustrates the principle:

$ExecutionContext.InvokeCommand.CommandNotFoundAction = 
    { 
        # second argument is the command that was missing:
        $p = $args[1]
        # do not try and find it elsewhere
        $p.StopSearch = $true

        $command = $p.CommandName
        
        # output audio message (make sure your audio is turned up)
        $sapi = New-Object -ComObject Sapi.SpVoice
        $sapi.Speak("Command $command not found.") 
    }

When you run the code above and then run a command that definitely not exists, you will hear an acoustic complaint (provided your audio is on and your speakers are turned up). When PowerShell cannot find a command, it looks for any script block that you assigned to CommandNotFoundAction and runs it.

The idea here was to improve command discoverability. For example, you may have taken the time to compile a list of popular commands and the module names that ship these commands. Then, your custom script block could try and find the missing command in that list, and let the user know the missing module name – or even download and install the module automatically.

Unfortunately, none of these things were adopted by the community since PowerShell introduced the action. Maybe now you feel intrigued to invent something more sophisticated than the sound message from above.


Tweet this Tip! Tweet this Tip!