Automation · PowerShell Automation
Try / Catch / Finally
Cheat sheet · https://pcornel.dk/topic.php?topic=5240
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
| Boundary | Try / Catch / Finally reference |
|---|---|
| Runtime identity | PowerShell edition/version + command/module source |
| Persistent intent | Script/module/config prerequisites under source control |
| Verification | Read-only discovery → execution evidence → independent target read-back |
| Output contract | Structured objects/streams before formatting |
| Failure boundary | Separate 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