views:

98

answers:

1

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

A: 

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))
FkYkko
Wow, that's crazy. I ended up just rewriting my script as a cmdlet in C# so I could override Stop().
fatcat1111

related questions