liveBook · Manning

Try-catch statement

As explained in Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

A try/catch construct is a PowerShell exception-handling structure that executes a try block and handles matching exceptions in catch blocks.

A try/catch statement runs risky PowerShell commands in a Try block and transfers control to a matching Catch block when a terminating exception occurs. Set ErrorAction to Stop when necessary, and process one computer at a time so one failure does not prevent the remaining targets from being attempted. section 15.4

Use the structure to keep failure handling deliberate:

  • Put dependent operations together in Try; when connection setup fails, skip queries and output generation. section 15.4
  • Catch can warn, retry with an alternate protocol, pass parameters recursively, or log the failure. section 15.4
  • Add Finally for cleanup or other work that must run whether Try succeeds or Catch handles an exception. section 15.7

Classified handling with cleanup

Use typed Catch blocks for known exception types, followed by an untyped Catch for anything else, and place guaranteed follow-up work in Finally. section 15.7

Try {
    # something here generates an exception
} Catch [Exception.Type.One] {
    # deal with that exception here
} Catch [Exception.Type.Two] {
    # deal with the other exception here
} Catch {
    # deal with anything else here
} Finally {
    # run something else
}

Browse the compact syntax pattern for typed catches, a general fallback, and an optional Finally block. section 15.7

How Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools covers it

How deep it goes
Explains terminating behavior, typed catches, fallback handling, Finally, and protocol retry while deferring broader exception mechanics.
Examples
Demonstrates New-CimSession, CIM queries, per-computer processing, alternate protocols, typed exceptions, and cleanup.
What it assumes
Assumes PowerShell functions, parameters, and commands; teaches terminating errors and structured handling through automation examples.
What you can do after
Apply it via PowerShell automation to stop dependent operations and implement targeted retry, warning, logging, or cleanup behavior.
How it connects
Connects exception handling with ErrorAction, warning messages, logging, protocol fallback, and Finally cleanup.

Also explained in

Compare how 10 books explain try-catch statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools. The section links point to the parts of the book it draws on.