Search code examples
powershellerror-handlingcustomization

Powershell errors: Is there a way to trap "command not found" errors into a custom function?


Background:

Suppose I have a powershell function that understands and interprets small_commands such as:

todolist.additem/title=shopping/body=get milk

Suppose further that I invoke the function like this:

myfunc [small_command goes here]

Question: Is there a way that I can type in the small_command and still have powershell invoke myfunc, even if I forget to prefix the small command with 'myfunc'? It seems like this could work if there is a way to trap "command not found" errors.

The general idea behind this question is the ability to recover from command not found errors by passing the offending command-line to a function that can try to "recover" from my input mistakes.

Update:


Solution

  • You can trap CommandNotFound using the trap statement and specifying which exception you are trapping

    & {
        trap [Management.Automation.CommandNotFoundException] 
        {
            "Code to Run here"; 
            (get-history);
            continue
        } 
        NotACommand
        }
    

    This code will set up a trap for the CommandNotFoundException and when it hits the NotACommand "command" it will call the trap statement and run the code in the block that has "Code to Run here" and then it will continue.

    The only thing I am not sure about would be accessing the commandline that threw the execption. Maybe using get-history.