我可以在 Powershell 中自定义 'not recognized as the name of a cmdlet' 错误吗?

Can I customise the 'not recognized as the name of a cmdlet' error in Powershell?

假设我在命令行中输入错误:

whih foo

功率shell 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

长消息对脚本很有用,但对于交互式 shell 使用,我想用更短的内容将其包装起来,例如:

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

我可以将错误包装起来并将其更改为更短的内容吗?

是的,您可以使用 a CommandNotFoundAction!

拦截 CommandNotFoundException
$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()
  }
}