首页 > 解决方案 > PowerShell REPL 中的全局 Try Catch 块

问题描述

我想在 PowerShell 控制台中创建一个全局错误处理程序,它始终可以在没有显式声明的情况下工作。

它的一种(但不仅是)用法是当用户输入某个目录路径(不带Set-Location)时,它会自动切换到该目录。现在它当然会引发错误。

在此处输入图像描述

是否可以实现这样的处理程序?我试图用 ( ) 包装所有内容,try catchprofileC:\Users\...\Documents\PowerShell\profile.ps1在 REPL 中没有帮助。

标签: powershellerror-handling

解决方案


对于通用的全局错误处理程序,您通常会使用trap.

不过,在这个特定的用例中,我们可以利用CommandNotFoundAction处理程序:

$ExecutionContext.InvokeCommand.CommandNotFoundAction = {
  param([string]$CommandName, [System.Management.Automation.CommandLookupEventArgs]$evtArgs)

  # Test if the "command" in question is actually a directory path
  if(Test-Path $CommandName -PathType Container){
    # Tell PowerShell to execute Set-Location against it instead
    $evtArgs.CommandScriptBlock = {
      Set-Location $CommandName
    }.GetNewClosure()
    # Tell PowerShell that we've provided an alternative, it can stop looking for commands (and stop throwing the error)
    $evtArgs.StopSearch = $true
  }
}

推荐阅读