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









