PowerShell Genie

Capture a terminating error

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Get-Item runs with -EA Stop, which promotes its non-terminating error into a terminating one so control transfers into the catch block.

The script

1PS> $Path = "C:\Scripts\Report.csv" # use a path that does not exist to see the catch block run
2PS> try { Get-Item $Path -ErrorAction Stop }
3PS> catch { Write-Warning $_.Exception.Message }

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 WARNING: The sample warning was emitted.
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    $Path = "C:\Scripts\Report.csv" # use a path that does not exist to see the catch block run try { Get-Item $Path -ErrorAction Stop } catch { Write-Warning $_.Exception.Message }
    1. Stage 1$PathPositional values or no named parameters

      How it works

      Get-Item runs with -EA Stop, which promotes its non-terminating error into a terminating one so control transfers into the catch block. Inside the catch, $_ is the ErrorRecord and its Exception.Message holds the text worth surfacing.

      Adapting it

      Read $_.Exception.GetType().FullName inside the catch to identify the exception type, then add typed catch blocks so a missing file and a permission denial can be handled differently.

      If the result is unexpected

      A catch block does not capture the error shown by a command.

      Many cmdlets emit non-terminating errors unless ErrorAction Stop is used for that operation.

      1. Run a deliberately failing test with ErrorAction Stop inside the try block.

      Validate the result

      The failure enters catch and preserves a useful error record.

      Keep the check reliable

      Keep try blocks focused and test both successful and failing control flow.

      Primary documentation

      Get-Item reference

      Practise the script’s building blocks

      Catch a missing service

      Request MissingService with -ErrorAction Stop inside try/catch. Return Service unavailable from the catch block.

      Review the lesson

      Continue
      Genie guideCapture a terminating error

      Get-Item runs with -EA Stop, which promotes its non-terminating error into a terminating one so control transfers into the catch block.