Detecting Key Press

by Jun 6, 2019

Sometimes it would be nice if a script was able to detect a key press without interfering with the script and its inputs. This way, you could add logic where pressing SHIFT would abort a script or enable verbose logging, and in your profile script, you could load modules and perform other adjustments based on whether you hold some key while PowerShell starts.

Which boils down to the question: what is the best and least interfering way of detecting key presses? Here it is:

Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName PresentationCore

1..1000 | ForEach-Object {
  "I am at $_"
  $isDown = [Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::LeftShift)
  if ($isDown)
  {
    Write-Warning "ABORTED!!"
    break
  }

  Start-Sleep -Seconds 1
} 

By adding the two default assemblies, your script gets access to the Windows.Input.Keyboard class which in turn has a IsKeyDown() method. It can check any key on your keyboard and returns $true when the key is currently down.

The example code above runs until the user presses the left shift key.

Twitter This Tip! ReTweet this Tip!