Gracefully stopping in Powershell

Viewed 32804

How do I catch and handle Ctrl+C in a PowerShell script? I understand that I can do this from a cmdlet in v2 by including an override for the Powershell.Stop() method, but I can't find an analog for use in scripts.

I'm currently performing cleanup via an end block, but I need to perform additional work when the script is canceled (as opposed to run to completion).

4 Answers

Here is recent, working solution. I use the if part in a loop where I need to control the execution interruption (closing filehandles).

    [Console]::TreatControlCAsInput = $true # at beginning of script

    if ([Console]::KeyAvailable){

        $readkey = [Console]::ReadKey($true)

        if ($readkey.Modifiers -eq "Control" -and $readkey.Key -eq "C"){                
            # tasks before exit here...
            return
        }

    }

Also note that there is a bug which leads KeyAvailable to be true upon start of scripts. You can mitigate by read calling ReadKey once at start. Not needed for this approach, just worth knowing in this context.

Related