Quantcast
Channel: QuickTip – Jaap Brasser's Blog
Viewing all articles
Browse latest Browse all 18

QuickTip: Read single key press using [System.Console] class

$
0
0

When building an interactive script capturing a single key press might be necessary. In the previous article, QuickTip: Read single key press from PowerShell console, I showed how this is possible using the $host variable. In this article I will show how to read a key press using the [System.Console] class and in particular the ReadKey method.

The following example uses ReadKey with a single argument, $true, to ensure that the result of the function is not output to the console. Omitting $true or passing on $false as an argument will result in the output being displayed in the console as well as stored in the variable. Have a look at the example here:

$KeyPress = [System.Console]::ReadKey($true)

Similarly to the $host object ReadKey method not only the key itself but also the modifiers are passed on to the console. Here is the result of this method:

PS> $KeyPress
 
KeyChar      Key      Modifiers
-------      ---      ---------
      J        J          Shift

The modifiers are slightly different from what the $host object output. To have a look at the possible values we dig a bit further into the object stored in $KeyPress:

PS> $KeyPress.Modifiers.GetType()
 
IsPublic      IsSerial                Name           BaseType
--------      --------                ----           --------
True              True    ConsoleModifiers        System.Enum
 
PS> [Enum]::GetNames([System.ConsoleModifiers])
Alt
Shift
Control

For more information about the System.Console class have a look at its MSDN entry: Console Class

TwitterLinkedInFacebookGoogle+RedditWordPressEmailTumblrPinterestHacker NewsShare


Viewing all articles
Browse latest Browse all 18

Trending Articles