2012-05-24 130 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()的其他代碼嗎? –

相關問題