2012-05-24 10 views
5

Los scripts de Powershell pueden terminarse fácilmente presionando ctrl-c. ¿Hay alguna forma de que un script de Powershell capture ctrl-c y le pida al usuario que confirme si realmente desea terminar el script?¿Hay alguna manera de atrapar ctrl-c y pedirle al usuario que confirme?

+0

Estoy buscando una manera de hacer lo contrario. Powershell SIEMPRE me pide que confirme la finalización. –

+0

¿Cómo lo hiciste para eso? –

+0

Así era cuando instalé Windows 7; ¡me vuelve loco! –

Respuesta

2

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

Si no desea utilizar una interfaz gráfica de usuario de mensaje para la confirmación, puede utilizar Read-Host en su lugar, o $ Host.UI.RawUI.ReadKey() como David mostró en su respuesta.

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

Entonces, ¿tendría que envolver esto con todo mi código? –

+0

¿No interferiría con otro código que usa $ host.ui.rawui.readkey()? –

Cuestiones relacionadas