O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

22.6. Detecting If Our Script Has Been Terminated by the User

Let's get back to our first example, which watches a folder for file delete operations, and see what happens if the user presses Ctrl+C while the script is listening for events. We will add a Write-Host call after the script that will get called after the script ends. Here is what we get:

PS C:\PowerShell> .\WatchDeletedFiles.ps1 ; Write-Host "Done"
PS C:\PowerShell>

Yes, we get nothing—not even the "Done" message. PowerShell terminates not only the script but the entire command that has been typed. Handling Ctrl+C is a weak spot in PowerShell 1.0, and that is why the PSEventing snap-in provides two cmdlets that can help us: Start-KeyHandler and Stop-KeyHandler. They can trap various ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required