24/7/365 Support

Read a Key of User Input in Windows PowerShell

Problem

You want your script to get a single keypress from the user.

Solution

For most purposes, use the [Console]::ReadKey() method to read a key: PS >$key = [Console]::ReadKey($true)

PS >$key

KeyChar
Key
Modifiers

h
H
Alt

For highly interactive use (for example, when you care about key down and key up), use:

PS >$key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") PS >$key

VirtualKeyCode Character ControlKeyState KeyDown 16 ...ssed, NumLockOn True

PS >$key.ControlKeyState ShiftPressed, NumLockOn

Discussion

For most purposes, the [Console]::ReadKey() is the best way to get a keystroke from a user, as it accepts simple keypresses—as well as more complex keypresses that might include the Ctrl, Alt, and Shift keys.

The following function emulates the DOS pause command:

function Pause

{ WriteHost NoNewLine "Press any key to continue . . . " [Console]::ReadKey($true) | OutNull WriteHost

}

If you need to capture individual key down and key up events (including those of the Ctrl, Alt, and Shift keys), use the $host.UI.RawUI.ReadKey() method.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say