PowerShell Genie

PowerShell try, catch and finally

Handle a failing operation explicitly and keep cleanup separate from success reporting.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

The example divides by zero, producing a terminating error that enters catch. The line that would print Result is skipped. Finally then runs during normal error unwinding, making it a place for releasing resources.

Many cmdlets report non-terminating errors by default. When a particular failure must enter catch, put -ErrorAction Stop on that command. Avoid changing the behavior of unrelated operations accidentally through a broad preference setting.

Inside catch, $_ is the ErrorRecord for the caught error. Preserve the message, target and operation context in your log. If the caller must know the operation failed, rethrow or return an explicit failure record instead of printing an error and then reporting success.

Finally is useful for disposing a stream or removing a temporary session. It does not mean a script can recover from forced process termination, and cleanup must not hide the original error with an avoidable second failure.

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.

try { $result = 10 / 0 Write-Output "Result: $result" } catch { Write-Output "Caught: $($_.Exception.Message)" } finally { Write-Output 'Finally always runs.' }
  1. Stage 1tryPositional values or no named parameters

    What happens

    Predict the two messages before inspecting the example: the caught error and the final cleanup message. In a real test, replace division by zero with a missing file read and compare behavior with and without -ErrorAction Stop.

    Worth remembering

    Decide which failures stop the operation, what the caller receives, and how resources are released.

    Primary documentation

    Microsoft Learn: try catch finally

    Try it

    Illustrative output · values vary by environment

    1PS> try {
    2PS> $result = 10 / 0
    3PS> Write-Output "Result: $result"
    4PS> }
    5PS> catch {
    6PS> Write-Output "Caught: $($_.Exception.Message)"
    7PS> }
    8PS> finally {
    9PS> Write-Output 'Finally always runs.'
    10PS> }

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Catches a terminating error and shows that finally runs either way.

      Show reference output

      Illustrative output · values vary by environment

      Caught: Attempted to divide by zero.
      Finally always runs.

      Practise this

      Catch a missing service

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

      Review the lesson

      Keep going

      Next: PowerShell ErrorRecord

      Check your understanding

      Get-Item reports an error but your catch block does not run. What should you check?

      Genie guidePowerShell try, catch and finally

      Handle a failing operation explicitly and keep cleanup separate from success reporting.