Skip to main content

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.

A France Dedicated Server provides an isolated environment for Windows-based applications, scripts, and administrative workloads, with direct control over the operating system and server configuration.

Help Category