Share via


Quit PowerShell script by pressing a defined key

Question

Thursday, June 16, 2011 9:48 AM

Hi experts,

I created an endless loop which tests the availability of our servers with the Test-Connection cmdlet.

I want to end the script by pressing a special key, for example CTRL+Q.

During stop event I want to log the stop time into file.

CTRL+C is not fine for me, because this way the script stops immediately and I have no chance to log the time.

I think using the command $host.ui.rawUI.KeyAvailable would be fine, but it works with every key, not just the one I want.

Thanks your advice in advance.

All replies (3)

Thursday, June 16, 2011 12:52 PM ✅Answered

Hi Robert,

Thanks for yor help.

I tested your script but I could not quit by pressing CTRL+q.

I can be something wrong with it.

Look at my version ( Remarks are in Hungarian :-) ):

 

clear-host

#
#  Endless loop will break by pressing the left CTRL+q
#

$Qkey = 81   # A "q" gomb kódja

For(;;)
  {
    Write-Host "O" -NoNewLine                       # "O" karakter kiírása soremelés nélkül.
   
    if ($host.ui.RawUi.KeyAvailable)                # Ha gomb lenyomás történt a billentyűzeten.
    {
      # A lenyomott gomb kódjának beolvasása a $key változóba.
      $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")
      if (($key.VirtualKeyCode -eq $Qkey) -AND ($key.ControlKeyState -match "LeftCtrlPressed"))
       {
         Write-Host ""           # Soremelés
         Write-Host "You pressed the key Ctrl+q, script ends."
         break                   # Kilépés a ciklusból.
       }
    }
    Start-Sleep -MilliSeconds 500   # Várakozás 500 ms -ig.
  }  # end of FOR   

 

 


Thursday, June 16, 2011 12:16 PM

Hi Filippo,

You need to capture the System.Management.Automation.Host.KeyInfo and check its VirtualKeyCode and ControlKeyState.

# your code

# .

# .

#.

# at the end of the script

Write-Host Press Ctrl-Q to Quit

do {

** $key = if ($host.UI.RawUI.KeyAvailable) {**

**  $host.UI.RawUI.ReadKey('NoEcho, IncludeKeyDown')**

** }**

} until ($key.VirtualKeyCode -eq 81 -and

**          $key.ControlKeyState -cmatch '^(Right|Left)CtrlPressed$')**

# log exit time

'Script stopped at ' + (Get-Date) >> C:\MyLog.log

 

  Robert Robelo  


Thursday, June 16, 2011 2:19 PM

Filippo,

I tested your script and works as expected. Make sure to run the script from the PowerShell Console, if you run it from Script Editors, Ctrl+Q may be already taken and you will not be able to intercept it.

  Robert Robelo