代码之家  ›  专栏  ›  技术社区  ›  mikemaccana

我可以自定义PowerShell中的“未识别为Cmdlet名称”错误吗?

  •  9
  • mikemaccana  · 技术社区  · 7 年前

    假设我在命令行中输入了错别字:

    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.
    

    我可以把错误包装起来改短一点吗?

    1 回复  |  直到 7 年前
        1
  •  10
  •   Mathias R. Jessen    7 年前

    CommandNotFoundException 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()
      }
    }
    
    推荐文章