2012-05-24 2 views
5

Powershell 스크립트는 ctrl-c를 눌러 사용자가 쉽게 종료 할 수 있습니다. Powershell 스크립트가 ctrl-c를 잡고 스크립트를 실제로 종료할지 여부를 묻는 방법이 있습니까?ctrl-c를 잡고 사용자에게 확인하도록 요청하는 방법이 있습니까?

+0

나는 그 반대의 방법을 찾고 있습니다. Powershell은 항상 해지를 확인해달라고 요청합니다. –

+0

어떻게 그렇게 했습니까? –

+0

Windows 7을 설치했을 때의 상태였습니다. 나를 미치게 해! –

답변

2

체크 아웃 this post on the MSDN forums. 당신이 확인을위한 GUI의 메시지 박스를 사용하지 않을 경우

[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 
      } 
     } 
    } 
} 

, 당신은 대신 읽기 호스트를 사용하거나 수 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()를 사용하는 다른 코드를 방해하지 않습니까? –

관련 문제