Gracefully stopping in Powershell
You could use the method described on here on PoshCode
Summary:
Set
[console]::TreatControlCAsInput = $true
then poll for user input using
if($Host.UI.RawUI.KeyAvailable -and (3 -eq
[int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
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."
}