Is there a way to catch ctrl-c and ask the user to confirm?

后端 未结 2 1950
甜味超标
甜味超标 2020-12-06 12:49

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

相关标签:
2条回答
  • 2020-12-06 13:12

    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.

    0 讨论(0)
  • 2020-12-06 13:27
    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; }
        }
    }
    
    0 讨论(0)
提交回复
热议问题