PowerShell – Press any key to continue

Context: This morning I was standing with Ben Gelens at the coffee machine since we’re both at the same customer.
Problem: Someone walked by and asked me if there is a way for PowerShell to ask for a key to press before it continues with the script… like a pause.
Together we replied: Read-Host. However, it seems that this scripter didn’t want a pop-up… which is what Read-Host gives… in PowerShell v2 at least.
In PowerShell 5 (which is what I’ve tested) it does not provide a pop-up. It also isn’t exactly like Press Any Key To Continue since it will only continue after an ENTER.
Solution: Upgrade to the latest and greatest version of Windows (or just upgrade WMF/PowerShell).
Workaround: See below.

Inside a PowerShell prompt you can do the following:

This is maybe a bit much for beginning scripters, so here’s an simpler version:

However, if you were to execute this in PowerShell ISE, you’ll get hit by an error:

It seems that the ReadKey method isn’t implemented in the host of Windows PowerShell ISE
So here’s some code that will offer a bit like the same functionality but in ISE (instead of any key, only ENTER will work):

Yes, Read-Host.
All my endeavours and investigations have led me to one single conclusion: Within Windows PowerShell ISE there is only one way to get functionality that resembles the Press Any Key To Continue behaviour and that is by using Read-Host.
This is because the console in ISE isn’t a console. It resembles one, but it isn’t the PowerShell console.
I don’t know if the terminology is correct, but I think it’s something that emulates a PowerShell console 🙂

Hope you find this information useful.

One comment

  1. ITMonkey says:

    quick and easy Pause function, load it in your profile to have it available in the console:

    Function Pause {
    Param([string]$Message=”Press any key to continue…, [switch]$LeaveMessage, [switch]$returnKey)

    #get cursor position so we can move it back later
    $pos = $host.UI.RawUI.cursorPosition;

    #flush the input buffer before pausing to clear any extraneous keypresses
    $host.UI.RawUI.FlushInputBuffer()

    write-host -NoNewLine:$(!$LeaveMessage) $Message

    #save the key pressed in case we need it
    $key = $host.UI.RawUI.ReadKey(“NoEcho, IncludeKeyUp”)

    # when a key is pressed and we continue, do we continue on the next line or remove the message
    if(!LeaveMessage) {
    #overwrite the message with empty space
    $host.UI.RawUI.CursorPosition = $pos
    write-host -NoNewLine (” ” *$Message.length)
    #set the cursor back to where is started
    $host.UI.RawUI.CursorPosition = $pos
    }

    #return the key if needed
    if ($returnkey) [ return $key }

    }

    Examples:
    Pause
    Pause -Message “Press something”
    Pause -LeaveMessage -returnkey

Leave a Reply

Your email address will not be published. Required fields are marked *