Press any key to continue [duplicate]

According to Microsoft's documentation, read-host lets the user type some input, and then press enter to continue. Not exactly the correct behavior if you want to have "Press any key to continue". (Wait... where's the Any key?!)

Is there a way to accomplish this? Something like read-char?

I've tried searching for "single character input" and "powershell input" to see if I could find a list of all ways to get input without much luck. And several Stack Overflow questions that looked hopeful use read-host which doesn't actually work for "press any key..." functionality.


Solution 1:

Here is what I use.

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Solution 2:

I've created a little Powershell function to emulate MSDOS pause. This handles whether running Powershell ISE or non ISE. (ReadKey does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox. This can sometimes be confusing, because the MessageBox does not always come to the forefront. Anyway, here it goes:

Usage: pause "Press any key to continue"

Function definition:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}