Search code examples
powershellinput

Read individual key presses in PowerShell


Using PowerShell, I would like to read the value of key presses as they occur, without the user having to press enter. For example, if the user presses '1' I would like the PowerShell script to react to the choice immediately without an 'enter'.

My research has turned up ReadKey,

$input = $Host.UI.RawUI.ReadKey('IncludeKeyDown');

But ReadKey returns much more information in the string than I require:

72,h,0,True

While I can parse the key press from this string, I'd prefer a more direct option. Does one exist?


Solution

  • Perhaps you could clarify a bit - but ReadKey returns a KeyInfo object not a string. KeyInfo contains VirtualKeyCode, Character, ControlKeyState and KeyDown members - all fields in your output string in that order. In fact, it looks like PowerShell has just called the .ToString() method in your output example. You will probably want to look at the Character property to find your desired character. Consider the following example where I press 1:

    $key = $Host.UI.RawUI.ReadKey()
    if ($key.Character -eq '1') {
      "Pressed 1"
    }