Global Try Catch block in PowerShell REPL

Viewed 198

I would like to create a global error handler in the PowerShell console that will always work without explicit declaration.

One (but not only) of its usages is when a user enters some directory path (without Set-Location) it will automatically switches to that directory. Now it raises an error of course.

enter image description here

Is it possible to implement such a handler? I tried to wrap everything with try catch in profile (C:\Users\...\Documents\PowerShell\profile.ps1) but it didn't help in the REPL.

1 Answers

For a generic global error handler, you'd normally use a trap.

In this specific use case though, we can take advantage of the CommandNotFoundAction handler:

$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
  }
}
Related