finally Block

noun

say it: “FY-nuh-lee BLOK” /ˈfaɪnəli ˈblɑk/

The last part of a try and catch, holding steps that run whatever happened, such as putting things back the way they were.

What is a finally block in PowerShell?

A finally block comes after try and catch, and runs whatever happens: after try worked, after catch, even after exit or Ctrl+C. That makes it the place to put things back, like turning off the oven whatever happened to the cake.

$start = Get-Location
Set-Location "$HOME\terminal-practice\mover\inbox"
try {
    Copy-Item 2026-10-03-groceries.pdf -Destination ..\backup-drvie\2026-10-03-groceries.pdf -ErrorAction Stop
}
catch { Write-Output "Couldn't copy it. It is still in the inbox." }
finally { Set-Location $start }   # back where you started, whatever happened
# Couldn't copy it. It is still in the inbox.

In a sentence

  • “Put the clean-up in a finally block, so it runs after exit 1 too.”
  • “The finally block takes Sam back to the mover folder even when the copy fails.”

Level: Journeyman · More PowerShell terms at this level

Updated

In other subjects