PowerShell: Capture Keystroke – Detect Pressed Key

Let’s say you have connected to your computer some human interface device (HID) that can simulate key presses (e.g. Arduino with a button) and you want to do some debug.

If you wonder how to capture a keystroke in Windows and detect which key has been pressed, this can be easily done from the PowerShell.

Cool Tip: Keyboard key press simulation using Arduino! Read more →

Capture Keystroke in PowerShell

To capture a key press in PowerShell, execute the following command:

PS C:\> $PressedKey = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

The command above captures a keystroke and records the information about the pressed key to the $PressedKey variable.

To print the information about the captured keystroke, execute:

PS C:\> $PressedKey

Sample output:

VirtualKeyCode      Character      ControlKeyState      KeyDown
--------------      ---------      ---------------      -------
            65              a            NumLockOn         True

If you have captured the press of a special key, e.g. F12, the “Character” field will be empty:

VirtualKeyCode      Character      ControlKeyState      KeyDown
--------------      ---------      ---------------      -------
           123                           NumLockOn         True

To get more details about the pressed key by its VirtualKeyCode, check the table of the virtual-key codes used by the Windows system here.

Cool Tip: How to respond “Yes” or “No” to prompts in Windows PowerShell & CMD automatically! Read more →

Leave a Reply