Powershell errors: is there a way to catch "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 call the function like this:

myfunc [small_command goes here]

      

Question: Is there a way that I can type in small_command and still have powershell call myfunc even though I forgot the small command prefix with "myfunc"? It looks like it might work if there is a way to catch command not found errors.

The general idea behind this question is to be able to recover commands without detecting errors by passing an offensive command line to a function that might try to "recover" from my input errors.

Note: Any criticism of this approach or alternative ideas is also encouraged.

+2


source to share


3 answers


You can capture CommandNotFound with trap statement and tell which exception you are using

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

      



This code will trap a CommandNotFoundException, and when it hits the NotACommand, it will call the trap statement and run the code in the "Code to Run Here" block, and then it will continue.

The only thing I'm not sure about this is access to the command line that started the execution. Perhaps using get-history.

+3


source


You will need a / script alias for each small_command ...

to run myfun small_command ...

.



Aliases can help with the main script looking at $MyInvocation

if it is not rewritten by mapping aliases.

+2


source


Unfortunately, PowerShell doesn't have a "last ditch" command hook. I've asked the team to consider doing this though, but it remains to be seen if v3 will contain such a feature.

However, you can emulate this behavior by adding some code to the prompt function that is called after each interactive command. Can you check $? which indicates the success of the last $ ^ command. Of course, this method will only work interactively, and it will be difficult to capture all the arguments.

-Oisin

+2


source







All Articles