Powershell Finally block skipped with Ctrl-C

Question:

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:

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:

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

Answer:

The proper answer is that Ctrl+C breaks pipeline, as is also stated in that link, and echo uses the pipeline to process its output. Therefore, once you Ctrl+C, writing to the pipeline causes the script block to err, and to not process any further commands. Therefore, do not use commands that send output to stdout directly, and there is a lot of them that indirectly use pipeline. Write-Host, on the other hand, does not use the pipeline, and thus does not throw an error.

Source:

Powershell Finally block skipped with Ctrl-C by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply