9

Say I make a typo on the command line:

whih foo

Powershell returns:

whih : The term 'whih' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ whih mocha
+ ~~~~
+ CategoryInfo          : ObjectNotFound: (whih:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

The long message is useful for scripts, but for interactive shell use, I'd like to wrap it with something shorter, like:

'whih' isn't a cmdlet, function, script file, or operable program.

Can I wrap the error and change it to something shorter?

4

1 回答 1

10

Yes, you can intercept the CommandNotFoundException with a CommandNotFoundAction!

$ExecutionContext.InvokeCommand.CommandNotFoundAction = {
  param($Name,[System.Management.Automation.CommandLookupEventArgs]$CommandLookupArgs)  

  # Check if command was directly invoked by user
  # For a command invoked by a running script, CommandOrigin would be `Internal`
  if($CommandLookupArgs.CommandOrigin -eq 'Runspace'){
    # Assign a new action scriptblock, close over $Name from this scope 
    $CommandLookupArgs.CommandScriptBlock = {
      Write-Warning "'$Name' isn't a cmdlet, function, script file, or operable program."
    }.GetNewClosure()
  }
}
于 2018-08-02T15:13:53.997 回答