Skip to main content

How to Handle Errors in PowerShell with try and catch

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

When a command can fail, such as reading a file that might be missing, you want to say what happened in your own words instead of a red error. PowerShell's try and catch do that. One detail decides whether it works at all: many cmdlets need -ErrorAction Stop. This guide handles a missing file, with real output from PowerShell 7.6.10.

Syntax​

Syntax
try {
<command> -ErrorAction Stop
}
catch {
<what to do; $_ is the error>
}
finally {
<optional: runs either way>
}
PartWhat it means
try { ... }The commands that might fail
-ErrorAction StopTurns a cmdlet's ordinary error into one that stops the command, so catch sees it
catch { ... }Runs when the try block fails. $_ is the error; $_.Exception.Message is its text
finally { ... }Optional. Runs whether there was an error or not

The about_Try_Catch_Finally page: "Use try, catch, and finally blocks to respond to or handle terminating errors in scripts."

Prerequisites​

  • PowerShell 7. This guide uses PowerShell 7.6.10.

Step 1: Catch a Missing File​

missing.txt doesn't exist:

PowerShell
try {
Get-Content missing.txt -ErrorAction Stop
}
catch {
"Could not read the file: $($_.Exception.Message)"
}
Output
Could not read the file: Cannot find path '/Users/you/source/ps-demo/missing.txt' because it does not exist.

PowerShell running the try and catch blocks, printing Could not read the file: Cannot find path because it does not exist.

Instead of PowerShell's red error, your message ran, with the error's own text after it.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out -ErrorAction StopGet-Content's error isn't a terminating error, so catch never ran: PowerShell printed its own error, then After the try block.Add -ErrorAction Stop to the cmdlet in try
Printing $_ aloneYou get the full error display, with Get-Content:, the line and its marker, instead of a short messageUse $_.Exception.Message

Troubleshooting​

SymptomLikely causeFix
catch doesn't run and the red error still showsThe cmdlet's error doesn't stop itAdd -ErrorAction Stop

FAQ​

What does finally do?​

It runs last, whatever happened. With a finally block added, the output was Caught it. and then This always runs.

Which errors does try catch?​

Terminating errors. The page: "PowerShell has two kinds of terminating errors: statement-terminating errors that stop the current statement and script-terminating errors that unwind the entire call stack Both kinds are caught by try/catch."

Conclusion​

Get-Content missing.txt -ErrorAction Stop inside try sent the error to catch, which printed Could not read the file: and the error's message. Without -ErrorAction Stop, catch didn't run.

Additional Resources​