views:

318

answers:

3

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.

Note: Also welcome is any critique of this approach or alternative ideas.

+2  A: 

You would need to alias/script each small_command ... to run myfun small_command ....

Aliases might help, with the main script looking at $MyInvocation, if this is not rewritten by alias mapping.

Richard
One reason for wanting to trap "command not found" was to get around aliasing each small_command, since those cannot be predicted ahead of time (e.g., todolist.additem/title=foobar can change from day to day and possibly never be repeated...)
dreftymac
While you can trap (catch) exceptions in a script I don't think this will work in general interactive use. And I'm not aware that PSH is sufficiently extensible to support the kind of extension you want directly.
Richard
+2  A: 

Unfortunately there is no "last ditch" command hook in powershell. I have asked the team to consider such a feature though, but it remains to be seen if v3 will contain such a feature.

That said, you could emulate this behaviour by adding some code into the prompt function which is called after each interactive command. You could test the $? system variable which indicates success of the last command $^. Of course this technique would only work interactively, and capturing all arguments is difficult.

-Oisin

x0n
+3  A: 

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.

Andy Schneider