我可以在Powershell中自定义"未识别为cmdlet的名称"错误吗?

mik*_*ana 9 powershell command-line powershell-core

假设我在命令行上输错:

whih foo
Run Code Online (Sandbox Code Playgroud)

Powershell返回:

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
Run Code Online (Sandbox Code Playgroud)

长消息对脚本很有用,但是对于交互式shell使用,我想用更短的东西包装它,比如:

'whih' isn't a cmdlet, function, script file, or operable program.
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*sen 10

是的,你可以拦截CommandNotFoundException一个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()
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @LotPings只有当搜索词不是`Verb-Noun`形式时(CommandDiscovery API在尝试_twice_后出错,一次出现,一次用'Get -`前置) (3认同)