Error Handling

The Silent Failure That Cost Hours

My deployment script ran successfully - or so I thought. Green text, "Deployment complete!" message, exit code 0. Perfect.

Except nothing was deployed. The script had failed silently halfway through, continued running, and reported success. Three hours later, users reported the application wasn't updated. I spent two hours debugging before I realized the issue: no error handling.

One try/catch block would have saved three hours of downtime and significant embarrassment.

Understanding PowerShell Errors

PowerShell has two types of errors:

Terminating Errors

Stop script execution immediately:

  • Syntax errors

  • Cmdlet failures with -ErrorAction Stop

  • Throw statements

  • Critical failures

Non-Terminating Errors

Script continues despite error:

  • File not found (by default)

  • Permission denied (by default)

  • Cmdlet failures without -ErrorAction Stop

Try/Catch/Finally

Basic Try/Catch

Catching Specific Exceptions

Finally Block

Always executes, regardless of errors:

The $Error Variable

PowerShell stores errors in $Error array:

ErrorAction Parameter

Control error behavior per cmdlet:

$ErrorActionPreference

Set default error behavior for script:

Throwing Custom Errors

Real-World Error Handling

Robust Script Template

API Call with Retry

Common Pitfalls

1. Not Using -ErrorAction Stop

Problem: try/catch doesn't catch non-terminating errors Solution: Use -ErrorAction Stop in try blocks

2. Catching All Errors Generically

Problem: Can't respond appropriately to different failures Solution: Catch specific exception types when possible

3. Swallowing Errors

Problem: Empty catch blocks hide problems Solution: Always log errors, even if handling them

Key Takeaways

  • Two error types: Terminating and non-terminating

  • Try/Catch/Finally: Standard error handling pattern

  • -ErrorAction Stop: Makes errors catchable

  • $Error variable: Stores error history

  • Throw: Create custom errors

  • Always log errors: Even if handling them

  • Use finally: For cleanup that must happen

What You've Learned

✅ Understanding error types in PowerShell ✅ Try/Catch/Finally blocks ✅ Using $Error variable and ErrorAction ✅ Throwing custom errors ✅ Building robust error handling ✅ Retry logic patterns ✅ Logging errors effectively

Next Steps

Now that your scripts handle errors gracefully, let's make them reusable. In Functions and Modules, you'll learn:

  • Creating functions

  • Advanced function features

  • Building modules

  • PowerShell Gallery

  • Code reusability patterns

Transform your scripts into shareable tools.


Ready to build reusable code? Continue to Functions and Modules

Last updated