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?
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 theCharacter
property to find your desired character. Consider the following example where I press 1:This will definitely do what you want.
This accepts a single character as input and has validation.
I have extracted out the essentials of the input and menu system and gave a few example menu items.
Please note: There are 2 modes for this to run in
MODE 1: Uses Read-Host, requires Enter, Runs in ISE. Use this for troubleshooting/building
MODE 2: Uses ReadKey, no Enter required, Does NOT run in ISE... You will need to run this in a PowerShell command line. The code below is currently in Mode 2.
Comment/UnComment the lines as needed to change the mode
The main part of the whole thing is:
What about a system that accepts 2 key presses?
Just a little addition here. Since we are talking about a SINGLE key press... how about a double key press? Well, this will work fine. Just stack up the ReadKey commands and assign variables to each, then combine them:
I look forward to questions or comments.
Regarding the use of
$Host.UI.RawUI.ReadKey('IncludeKeyDown');
Goyuix answer should be marked as the right answer.I found the
$Host.UI.RawUI.ReadKey
rather long and wanted to use[console]
.But was a bad decision. This is a warning. Some might know how to use it right.
Key will give you for pressing some keys
Additionally the similar looking
[console]::ReadKey
it will the Key Property.