有没有办法捕获ctrl-c并要求用户确认? [英] Is there a way to catch ctrl-c and ask the user to confirm?
本文介绍了有没有办法捕获ctrl-c并要求用户确认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用户可以通过按ctrl-c轻松终止Powershell脚本。 Powershell脚本是否可以捕获ctrl-c并要求用户确认他是否真的想终止该脚本?
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 wanted to terminate the script?
推荐答案
结帐这篇文章放在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(),如David在其答案中所示。
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.
这篇关于有没有办法捕获ctrl-c并要求用户确认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文