Gracefully stopping in Powershell

The documentation for try-catch-finally says:

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.

See the following example. Run it and cancel it by pressing ctrl-c.

try
{
    while($true)
    {
        "Working.."
        Start-Sleep -Seconds 1
    }
}
finally
{
    write-host "Ended work."
}

Leave a Comment