PowerShell try, catch and finally
Handle a failing operation explicitly and keep cleanup separate from success reporting.
Documentation: Microsoft Learn
Overview
The example divides by zero, producing a terminating error that enters catch. The line that would print Result is skipped. Finally then runs during normal error unwinding, making it a place for releasing resources.
Many cmdlets report non-terminating errors by default. When a particular failure must enter catch, put -ErrorAction Stop on that command. Avoid changing the behavior of unrelated operations accidentally through a broad preference setting.
Inside catch, $_ is the ErrorRecord for the caught error. Preserve the message, target and operation context in your log. If the caller must know the operation failed, rethrow or return an explicit failure record instead of printing an error and then reporting success.
Finally is useful for disposing a stream or removing a temporary session. It does not mean a script can recover from forced process termination, and cleanup must not hide the original error with an avoidable second failure.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
try {
$result = 10 / 0
Write-Output "Result: $result"
}
catch {
Write-Output "Caught: $($_.Exception.Message)"
}
finally {
Write-Output 'Finally always runs.'
}- Stage 1try
Positional values or no named parameters
What happens
Predict the two messages before inspecting the example: the caught error and the final cleanup message. In a real test, replace division by zero with a missing file read and compare behavior with and without -ErrorAction Stop.
Worth remembering
Decide which failures stop the operation, what the caller receives, and how resources are released.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
Catches a terminating error and shows that finally runs either way.
Show reference output
Illustrative output · values vary by environment
Caught: Attempted to divide by zero. Finally always runs.
Practise this
Catch a missing service
Request MissingService with -ErrorAction Stop inside try/catch. Return Service unavailable from the catch block.
The sandbox is visible now. Sign in with Google only when you run or check a task; commands and temporary files are discarded when you leave.
Run a command to inspect its result.
Inspect starting data
Supported syntax
Virtual files
Keep going
Next: PowerShell ErrorRecordCheck your understanding
Get-Item reports an error but your catch block does not run. What should you check?
Catch handles terminating errors. Use -ErrorAction Stop on a command when you need its non-terminating error to enter catch. Finally performs cleanup.