Press any key to continue

Powershell

Powershell Problem Overview


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.

Powershell Solutions


Solution 1 - Powershell

Here is what I use.

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

Solution 2 - Powershell

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")
    }
}

Solution 3 - Powershell

Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Example:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff BView Question on Stackoverflow
Solution 1 - PowershellKnuckle-DraggerView Answer on Stackoverflow
Solution 2 - PowershellJerry GView Answer on Stackoverflow
Solution 3 - Powershelluser189198View Answer on Stackoverflow