【问题标题】:Can I customise the 'not recognized as the name of a cmdlet' error in Powershell?我可以在 Powershell 中自定义“不被识别为 cmdlet 的名称”错误吗?
【发布时间】:2019-01-10 09:23:31
【问题描述】:

假设我在命令行打错字:

whih foo

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

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

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

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

【问题讨论】:

  • 不得不问,但我会假设 try 块不是您想要的(为此目的而设计的),并且您希望更改消息的实际措辞
  • @Matt 没错,它是用于交互式使用的。所以是的,我不想将每个命令都包装在 try 块中。只是为$profile寻找东西

标签: powershell command-line powershell-core


【解决方案1】:

是的,你可以用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()
  }
}

【讨论】:

  • 这比我想做的要容易得多。
  • 代理 Format-Default 或查找与该消息关联的语言文件/数据。我不知道你可以制作这样的触发器。
  • @Matt 啊,这既聪明又非常不可取:P
  • 确实如此。然而,这是我能想到的唯一选择。现在我需要研究你在这里做了什么,看看我还能如何使用它:)
  • @LotPings 仅当搜索词不是 Verb-Noun 形式时(CommandDiscovery API 在尝试 两次 后出错,一次按原样,一次以 Get- 为前缀)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2020-06-12
  • 2016-01-28
  • 2017-03-26
相关资源
最近更新 更多