Press Any Key to Continue in PowerShell

Solutions for PowerShell Integrated Scripting Environment(ISE) and Command Line Console

Using Read-Host Cmdlet

Use the Read-Host command to enable press any key to continue in PowerShell.

The Read-Host cmdlet is the most commonly used and easy to understand. We used it to pause execution and prompt the user to get the input line from the PowerShell console. Remember, we must press Enter to exit from the pause mode.

Here, the -Prompt parameter was used to specify a prompt’s text, allowing the user to type a string. If the string contains spaces, then enclose it within the quotation marks.

We can also use the Read-Host cmdlet to prompt users to get secure data, for instance, passwords, because we can save the received input string as a secure string using the -AsSecureString parameter as follows:

Remember, the Read-Host can only accept 1022 characters as the input given by the user.

Using Message Box UI

This approach is practical when we want to enable only one key to continue in PowerShell. So, to allow that:

  • Use New-Object with the -ComObject parameter to specify the COM object’s programmatic identifier.
  • Use the .Popup() function to display text in a pop-up window.

press any key to continue in powershell - message box ui

We can use the New-Object cmdlet to create an instance of a COM object or .NET framework. We can write either the ProgID of the COM Object or the type of a .NET framework class.

For the above code fence, we used New-Object to create an instance of the COM object. Then, we specified the -ComObject parameter with the New-Object cmdlet to write the programmatic identifier (ProgID) of the COM object, which was the WScript.shell and saved the reference in $Shell variable.

Next, we used the Popup() method to show text in the pop-up message box. We can only use the Popup() method by chaining it with the WshShell Object, which is $Shell in our case. The .Popup() method took four values; let’s understand them below:

  • strText– Contains a string type value, which is the text message displayed in our pop-up message box. We used Press OK to continue as the value for the strText parameter.
  • nSecondsToWait – It is an optional parameter that contains a numeric value denoting the maximum time (in seconds) to display a pop-up message box. If this parameter is set to 0, which is its default value, the message box will be visible until the user presses OK or X. The message box will also be closed if users hit Enter from their keyboard.
  • strTitle – It also holds a string type value, used as the title for the pop-up message box.
  • nType – An optional parameter that holds a numeric value representing the type of icons/buttons we want to use in our pop-up message box. For instance, we used 0 to show the OK button. You can find different decimal values for different types of controls (buttons) and icons here.

Finally, we used $Button to hold a numerical value, which is returned by the .Popup() method. This numerical value denotes the number of buttons the user clicks to dismiss the pop-up message box.

Note: We can also specify Hexa-decimal values for the nType parameter.

Until this point, we have learned various approaches that works in PS-ISE (PowerShell Integrated Scripting Environment), a graphical user interface and front-end hosting. However, below are a few ways that will only work on PowerShell Command Line Console.

Solutions for PowerShell Command Line Console

Using ReadKey() Method with/without [void]

Use the ReadKey() method to enable press any key to continue in PowerShell.

The above command waits until the user press any key to continue. Note that this command will not accept the individual modifier keys (Alt, Ctrl, and Shift).

Let’s break down this command into parts to learn it more clearly. First, the ReadKey($true) wait, which means blocked on a thread issuing a ReadKey method, and got the function or character key pressed by a user.

Here, the function or character key can be single or in combination with modifier keys (Alt, Ctrl, and Shift). However, if you press any modifier key only, it will not result in the ReadKey method return.

We passed the $true argument to the ReadKey() method because we did not want to display the pressed key in the console window. But this is optional; we can omit this argument or pass $false if we’re going to show the pressed key in your console window. See the following example.

We used the static member operator (::) to call a .NET framework’s static class named System.Console. We can also use the :: operator to call static properties of the .NET framework. Now, what is System.Console?

In the .NET framework, we have a class named Console, located in the System namespace. The System.Console class lets us programmatically access stdin, stderr and stdout in the console application. Here, stdin, stderr, and stdout represents input, error and output streams for the console application.

Now, the question is, why are we using [void]? Before answering this question, use the following command without [void] and see its output.

See, we are getting the information about the pressed key. Now, try to recall where we learned that the $true argument is passed to the ReadKey() method when we don’t want to display the data about the pressed key on the console, but the above example behaves entirely in a different way; why?

It is because any expression or command that outputs or returns some data is implicitly displayed to the output stream (also called success stream), which goes to the host by default, a terminal (console window) in which the PowerShell session runs.

We must suppress it if we do not want to output that data. To suppress, we have various options, which include ... | Out-Null, ... > $null, [void] (...), and $null = .... So, we used [void] to suppress the data returned by [System.Console]::ReadKey($true). Note that the [void] represents the intent to suppress an output upfront.

Now, think of a situation where we have to display the pressed key and relevant data, which is stored in the form of an System.ConsoleKeyInfo object. In that case, we use the following command.

Using RawUI.ReadKey() Method

To enable press any key to continue in PowerShell:

  • Use Write-Host to write a user-friendly message.
  • Use RawUI.ReadKey() to read the keystroke from the keyboard device.

Here, we used the Write-Host cmdlet to display a user-friendly message on the PowerShell console and to guide the user about what s/he is supposed to do.

Next, we used the -NoNewLine parameter to concatenate the input object to form an output. No newlines or spaces will be inserted between the output strings. Likewise, no new line will be added after the last output string.

After that, we used the $Host.UI.RawUI.ReadKey() method, which is similar to the [Console]::ReadKey() that we learned in the previous section. It can accept any key, even modifier keys, which includes Ctrl, Shift, Alt, and other modifier keys.

Note that we can use RawUI.ReadKey() with and without ReadKeyOptions, which includes IncludeKeyDown, IncludeKeyUp, NoEcho, and AllowCtrlC. So, for the above code example, we used ReadKey() with ReadKeyOptions and got data as an output which is saved in the form of KeyInfo object.

If you are interested in more technical details, let me tell you that the $Host.UI is a System.Management.Automation.Internal.Host.InternalHostRawUserInterface object. In contrast, the $Host is an automatic variable whose type is System.Management.Automation.Internal.Host.InternalHost. Therefore, we can use the $Host.GetType().FullName command to know the type of the $Host variable.

Using cmd /c pause Command

Use the cmd /c pause command to enable press any key to continue in PowerShell.

The above command enabled and displayed Press any key to continue ... and wait for the user to press any key. It returns once the user presses any key, excluding modifier keys.

Using timeout /t Command

Use the timeout /t command to enable press any key to continue and wait for the specified number of seconds or user’s input in PowerShell.

The above timeout command paused the execution for a time frame or infinite time. Here, we used /t to specify the time in seconds. Note that the given time must be from the -1 to 99999 range. So, for example, the above command will wait for 10 seconds if no key is pressed.

We can use the following command to keep waiting for an infinite time until the user presses any key excluding Fn, Ctrl, and Alt, etc.

That’s all about how to press any key to continue in PowerShell.

Was this post helpful?

Related Posts

  • Call Function with Parameters in PowerShell
    08 January

    PowerShell – Call Function with Parameters

    Table of ContentsUsing Positional ParametersUsing Named Parameters Using Positional Parameters To call a function, use positional parameters separated by space. Please note that you need to pass parameters in sequence while calling the function. [crayon-63bb863fd5b8a923101265/] [crayon-63bb863fd5b90472263761/] Microsoft’s PowerShell consists of a command-line shell and scripting language. It is based on the .NET framework for task […]

  • 08 January

    PowerShell – Unzip File

    Table of ContentsUsing Expand-Archive CmdletUsing System.IO.Compression.ZipFile NamespaceUsing 7Zip Module Using Expand-Archive Cmdlet Use the Expand-Achrive cmdlet to unzip a file/folder in PowerShell. [crayon-63bb863fdd34a248535663/] Please note that Expand-Archive cmdlet is available from PowerShell 5 onwards. Print envionment variable $PSVersionTable.PSVersion to check version of your PowerShell. We used the Expand-Achrive cmdlet to unzip a folder from the […]

  • PowerShell - Write log to file
    07 January

    PowerShell – Write to Log File

    Table of ContentsUsing the TranscriptUsing the Add-Content CmdletUsing the Write-Output CmdletUsing the Out-File Cmdlet Using the Transcript To write to a log file using Transcript: Use the Start-Transcript cmdlet to start writing to the log file. Perform operations normally without writing anything to the file. Use the Stop-Transcript to stop the transcript. [crayon-63bb863fd7de9833916446/] [crayon-63bb863fd7def086197155/] A […]

  • Get size of folder in PowerShell
    07 January

    PowerShell – Get Size of Folder

    Table of ContentsUsing Get-ChildItem with Measure-ObjectGet File Size of a Certain TypeGet Directory Size, Including Sub-foldersUsing the PSFolderSize Module Using Get-ChildItem with Measure-Object Use Get-ChildItem with the Measure-Object cmdlet to get the size of files in the specified directory. [crayon-63bb863fdda0d232125479/] [crayon-63bb863fdda13356678206/] Please note that above sum doesn’t include subfolder sizes. If you want to include […]

  • PowerShell - read file line by line
    07 January

    PowerShell – Read File Line by Line

    Table of ContentsUsing Get-Content CmdletUse Get-Content Cmdlet to Read Partial DataUse Get-Content Cmdlet with -Like OperatorUsing switch StatementUsing the ReadLines() of [System.IO.File] ClassUsing the StreamReader Class Using Get-Content Cmdlet Use the Get-Content cmdlet to read file line by line in PowerShell. [crayon-63bb863fd4f93191499150/] [crayon-63bb863fd4f99278852322/] We used the Get-Content cmdlet to read the specified file line by […]

  • Multiline comment in PowerShell
    05 January

    PowerShell – Multiline Comment

    Table of ContentsUsing <# #> TagsUsing Shortcut Keys Using <# #> Tags Use the <# tag at the beginning of comments and the #> tag at the end of comments to create multiline comments in PowerShell scripts. All lines inside the comment block are part of the comments. [crayon-63bb863fde1fd328315371/] In programming, we use a comment […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.