Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Try / Catch / Finally

Direct 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.

When to use this

Use this when catching and cleaning up after PowerShell errors.

First 30 seconds

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.

Operational verification

try → error → catch → finally

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
PowerShell 7.6/current
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformPowerShell 7.6/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when catching and cleaning up after PowerShell errors.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points
  • try runs code, catch handles errors, finally always runs.
  • Catch specific exception types first.
  • Only terminating errors are caught.
Key checks
  • 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
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
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

PowerShell 7.6/current 7.6/currentMinimal authored PowerShell pattern for Try / Catch / Finally

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() }
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docPowerShell 7.6/current 7.6/current

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%
Embedded reference data

Quick lookup tables

Try / Catch / Finally · PowerShell operational reference

Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.

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
Depth when you need it

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.

Confirmation

Confirm action

Continue?