【问题标题】:Is there a way to catch ctrl-c and ask the user to confirm?有没有办法捕捉 ctrl-c 并要求用户确认?
【发布时间】:2012-05-30 19:32:50
【问题描述】:

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

【问题讨论】:

  • 我正在寻找一种相反的方法。 Powershell 总是要求我确认终止。
  • 你是怎么做到的?
  • 这就是我安装Windows 7时的样子;它让我发疯!

标签: powershell copy-paste


【解决方案1】:

结帐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()。

【讨论】:

    【解决方案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; }
        }
    }
    

    【讨论】:

    • 不会干扰其他使用$host.ui.rawui.readkey()的代码吗?
    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 2022-07-26
    相关资源
    最近更新 更多