PowerShell REPL 中的全局 Try Catch 块

Global Try Catch block in PowerShell REPL

我想在 PowerShell 控制台中创建一个全局错误处理程序,它无需显式声明即可始终运行。

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

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

对于通用的全局错误处理程序,您通常会使用 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
  }
}