Cleverly Aborting Endless Loop

by Mar 11, 2016

In a previous tip you have seen how an endless loop can be used to continuously monitor things – until PowerShell is closed, or a user presses CTRL+C to abort the script. There is even a way for PowerShell to detect abortion. This way, you can control what happens when the script is aborted. Simply use a try…finally-block.

The example prints out a line of dots, and if you get bored enough to press CTRL+C, the script complains that you aborted it – just make sure you turned the volume up:

    Write-Host '.' -NoNewline
    Start-Sleep -Milliseconds 800
  } while ($true)
  $sapi = New-Object -ComObject Sapi.SpVoice
  $sapi.Speak('Hey, you aborted me dammit!')

The exciting part is that the finally block will also execute when you close PowerShell.

Twitter This Tip! ReTweet this Tip!