Use this when catching and cleaning up after PowerShell errors.
Try / Catch / Finally
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.
1. try/catch catches terminating errors.
2. Use -ErrorAction Stop to make errors catchable.
3. finally always runs (cleanup).
4. Catch specific types where possible.
5. Rethrow with throw when unhandled.
try → error → catch → finally
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
Test at least one successful path, a matching terminating failure and an unexpected failure. Inside catch, inspect the ErrorRecord and exception type; in finally, verify cleanup actually occurred. For commands that normally emit non-terminating errors, explicitly test whether your -ErrorAction policy produces the control flow you expect.
Step 2 Common mistakes Narrow the fault
- Empty catch blocks.
Step 3 Where it fails Narrow the fault
try/catch handles terminating PowerShell errors, not arbitrary negative business results. A REST API can return a successful HTTP response whose body reports a failed business operation, and a native program can return nonzero without automatically becoming a catchable ErrorRecord. Separate language error semantics from external outcome semantics.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- try runs code, catch handles errors, finally always runs.
- Catch specific exception types first.
- Only terminating errors are caught.
try { Get-Item C:\nope -ErrorAction Stop } catch { $_.Exception.Message }— catch example- finally for cleanup — resources
- Specific exception types — precise handling
ReferenceWhy it matters1 section · depth on demand
In depth
try/catch/finally handles terminating errors: try contains the work, catch blocks handle specific exception types, and finally always runs for cleanup — closing sessions, releasing locks, removing temporary files.
$session = $null
try {
$session = New-PSSession -ComputerName $Server -ErrorAction Stop
Invoke-Command -Session $session -ScriptBlock { Restart-Service W3SVC -ErrorAction Stop }
}
catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
Write-Warning "$Server unreachable: $($_.Exception.Message)"
}
catch {
Write-Error "Unexpected failure on ${Server}: $_"; throw
}
finally {
if ($session) { Remove-PSSession $session }
}
Catch specific exception types first and general errors last; re-throw (throw) when the caller needs to know the operation failed.
ReferenceImportant terms & boundaries2 sections · depth on demand
Platform, version and operating-envelope scope
PowerShell 5.1/7+, module versions and remoting endpoint behavior vary by host/platform.
PowerShell mechanics
try monitors a statement list for terminating errors, catch matches terminating errors by exception type or as a general handler, and finally executes cleanup regardless of whether the try body succeeded or a catch handled an error. Non-terminating errors normally do not enter catch unless they are promoted, for example with -ErrorAction Stop where applicable.
ReferenceConfiguration & state1 section · depth on demand
Authoring and lifecycle
Use the narrowest catch blocks that can make a meaningful recovery decision, order specific exception handlers before general ones, and keep cleanup such as disposing resources in finally. Re-throw when the current layer cannot satisfy the required outcome. Avoid catch-all handlers that only print a message and then return success.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
Assumptions: Review target identity, permissions and environment before mutation.
try { Get-Item -LiteralPath $Path -ErrorAction Stop } catch [System.Management.Automation.ItemNotFoundException] { throw } finally { $resource?.Dispose() }Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Microsoft Learn documentation reviewed for bounded PowerShell reference claims. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.6 · confidence 94%Quick lookup tables
Try / Catch / Finally · PowerShell operational reference
Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.
| 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 |
Deep reference
Healthy vs suspicious evidence
Output interpretation
A catch block running is evidence about control flow, not evidence of successful recovery. finally can run even when output is not visible due to pipeline termination or host behavior. Preserve the original exception/error metadata before replacing it with custom text, and ensure the final caller-visible status still indicates failure when recovery is incomplete.