Detecting Key Presses

by Jul 11, 2019

It may be useful for PowerShell to know whether a given key is currently pressed. This way, your profile script could, for example, do things during PowerShell startup based on keys you hold. For example, when you hold the left CTRL key while launching PowerShell, your profile script could preload certain modules or connect you to servers.

Here is how PowerShell detects pressed keys:

# this could be part of your profile script

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

# assume the script is doing something
# (so you can get ready and press left Ctrl!)
Start-Sleep -Seconds 2

# choose the key you are after
$key = [System.Windows.Input.Key]::LeftCtrl
$isCtrl = [System.Windows.Input.Keyboard]::IsKeyDown($key)

if ($isCtrl)
    'You pressed left CTRL, so I am now doing extra stuff'

Twitter This Tip! ReTweet this Tip!