Powershell Finally block skipped with Ctrl-C

Viewed 4557

I'm writing a monitoring script in Powershell using a Try/Finally to log a message should the script end. The script is intended to run indefinitely, so I want a way to track unintended exiting.

Every other StackOverflow post and Help page I've checked states:

A Finally block runs even if you use CTRL+C to stop the script. A Finally block also runs if an Exit keyword stops the script from within a Catch block.

In practice, I have not found this to be true. I'm using the following contrived example to test this out:

Try {
    While($True) {
        echo "looping"
        Start-Sleep 3
    }
} Finally {
    echo "goodbye!"
    pause
}

The Finally block here is skipped every time after a Ctrl+C (no echo, no pause), both when running as a saved script or when executing through the built-in Powershell ISE. The only output I ever get is:

looping
looping
...(repeat until Ctrl-C)

I've clearly missed something, but I have no idea what it is, especially in a code snippet as small as this.

2 Answers
Related