Pcornel
Automation · PowerShell Automation

Try / Catch / Finally

Cheat sheet · https://pcornel.dk/topic.php?topic=5240

Back to the Topic

Answer

try/catch/finally in PowerShell runs code, catches terminating errors (optionally by exception type) and always runs the finally block for cleanup, such as closing sessions.

Remember

  • try runs code, catch handles errors, finally always runs.
  • Catch specific exception types first.
  • Only terminating errors are caught.

First checks

  • try { Get-Item C:\nope -ErrorAction Stop } catch { $_.Exception.Message } — catch example
  • finally for cleanup — resources
  • Specific exception types — precise handling

Verify in this order

try → error → catch → finally

Where it usually breaks

Script/input → command/module binding → local/remoting session → request accepted → command result → target object read-back → effective runtime state → workload.

Try / Catch / Finally · PowerShell operational reference

BoundaryTry / Catch / Finally reference
Runtime identityPowerShell edition/version + command/module source
Persistent intentScript/module/config prerequisites under source control
VerificationRead-only discovery → execution evidence → independent target read-back
Output contractStructured objects/streams before formatting
Failure boundarySeparate engine/binding from transport/API/native and target-state failures

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=5240

Confirmation

Confirm action

Continue?