有没有办法捕获ctrl-c并要求用户确认?

时间:2012-05-24 08:24:16

标签: powershell copy-paste

用户按ctrl-c可以轻松终止Powershell脚本。有没有办法让Powershell脚本捕获ctrl-c并要求用户确认他是否真的要终止脚本?

2 个答案:

答案 0 :(得分:4)

结帐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
            }
        }
    }
}

如果你不想使用GUI MessageBox进行确认,你可以使用Read-Host,或者像David在他的回答中所示的$ Host.UI.RawUI.ReadKey()。

答案 1 :(得分:2)

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; }
    }
}