Capture a terminating error
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
Script reader
Inspect before you run
Inspect the script below. It does not run in this browser.
Inspection only — no command has run.
Show reference output
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 }- Stage 1$Path
Positional 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.
- 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
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.
The sandbox is visible now. Sign in with Google only when you run or check a task; commands and temporary files are discarded when you leave.
Run a command to inspect its result.