Wait For Key Press

by Jul 8, 2009

Sometimes you'd like to wait for a key press. The easiest way is to use Read-Host like this:

Read-Host 'Please press ENTER' | Out-Null

Problem here is: Read-Host accepts more than one key and only continues after you press ENTER. To implement a real "one key press only" solution, you need to access the PowerShell raw UI interface. This interface has a property called KeyAvailable which returns $true once a key was entered.

Here is a Wait-KeyPress function which wraps all the things necessary to wait for a keypress:

function Wait-KeyPress($prompt='Press a key!') {
Write-Host $prompt

do {
Start-Sleep -milliseconds 100
} until ($Host.UI.RawUI.KeyAvailable)

$Host.UI.RawUI.FlushInputBuffer()
}

Wait-KeyPress

A loop queries KeyAvailable until it returns $true, indicating that a key was pressed. Start-Sleep delays the loop by 100ms to minimize CPU load.

Finally, FlushInputBuffer() clears the input buffer and removes the pressed key from that buffer which is necessary to prevent the entered key to show up in subsequent inputs.