Tag Archives: System.Console

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

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

Share

QuickTip: Have the PowerShell console beep

Using the Beep method of the System.Console namespace it is possible to have the PowerShell console produce a beeping sound. Occasionally it can be useful to have the console get your attention by producing a sound. The following line of code will produce a short ‘beep’:

[System.Console]::Beep()

It is also possible to specify two parameters for this method, the first parameter is the tone measured in hertz and the second is the duration in milliseconds. Here is an example of a beep at 6000hz for half a second:

[System.Console]::Beep(6000,500)

for more information about this class, please refer to the MSDN entry of this method, which is available here:
Console.Beep method

Share