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 ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.