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

And*_*ehm 6 powershell copy-paste

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

dea*_*dog 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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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