2012-05-24 131 views
5

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

+0

我正在寻找一种方法来做相反的事情。 Powershell总是要求我确认终止。 –

+0

你是怎么做到的? –

+0

这就是我安装Windows 7时的情况;它让我疯狂! –

回答

2

结帐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消息框的确认,你可以使用读 - 主机,而不是,或$ 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; } 
    } 
} 
+0

所以我不得不在我所有的代码中包装这个? –

+0

它不会干扰使用$ host.ui.rawui.readkey()的其他代码吗? –

相关问题