8

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

4

2 回答 2

4

在 MSDN 论坛上查看此帖子

[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 或 $Host.UI.RawUI.ReadKey() 正如大卫在他的回答中所展示的那样。

于 2013-05-06T23:26:49.743 回答
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; }
    }
}
于 2012-05-24T08:56:10.647 回答