Powershell scripts can easily be terminated by the user pressing ctrl-c. Is there a way for a Powershell script to catch ctrl-c and ask the user to confirm whether he really wanted to terminate the script?
            Asked
            
        
        
            Active
            
        
            Viewed 1.4k times
        
    10
            
            
        - 
                    I'm looking for a way to do the opposite. Powershell ALWAYS asks me to confirm termination. – David Murdoch Aug 17 '12 at 20:10
 - 
                    How did you get it to do that? – Andrew J. Brehm Aug 18 '12 at 18:48
 - 
                    It's just how it was when I installed Windows 7; it drives me crazy! – David Murdoch Aug 19 '12 at 03:03
 
2 Answers
4
            Checkout this post on the MSDN forums.
[console]::TreatControlCAsInput = $true
while ($true)
{
    write-host "Processing..."
    if ([console]::KeyAvailable)
    {
        $key = [system.console]::readkey($true)
        if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C"))
        {
            Add-Type -AssemblyName System.Windows.Forms
            if ([System.Windows.Forms.MessageBox]::Show("Are you sure you want to exit?", "Exit Script?", [System.Windows.Forms.MessageBoxButtons]::YesNo) -eq "Yes")
            {
                "Terminating..."
                break
            }
        }
    }
}
If you don't want to use a GUI MessageBox for the confirmation, you can use Read-Host instead, or $Host.UI.RawUI.ReadKey() as David showed in his answer.
        deadlydog
        
- 22,611
 - 14
 - 112
 - 118
 
3
            
            
        while ($true)
{
    Write-Host "Do this, do that..."
    if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
    {
            Write-Host "You pressed CTRL-C. Do you want to continue doing this and that?" 
            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
            if ($key.Character -eq "N") { break; }
    }
}
        David Brabant
        
- 41,623
 - 16
 - 83
 - 111
 
- 
                    Would it not interfere with other code that uses $host.ui.rawui.readkey()? – Andrew J. Brehm May 24 '12 at 11:27