Home PowerShell How To Accomplish a PowerShell Pause

How To Accomplish a PowerShell Pause [Step-By-Step]

There are a variety of reasons to halt the running of a script. A script may need to be put on hold for user input, to reduce the pace of execution, or to wait in turn while another process finishes. There are several ways to attain a PowerShell pause. 

The manner of halting or pausing a script you decide on will come with its pros and cons, depending on your end goal.

PowerShell’s new cross-platform capability adds additional options for users. Because PowerShell often acts as the glue that binds much technology, the Linux command-line offers its own alternatives for pausing processes that may be included in PowerShell.

Ways to Accomplish a PowerShell Pause

What are the various methods for pausing script execution? The ability to pause will be broken down into non-native and native commands in this article.

I  use the term “native” to refer to PowerShell or.NET built-in procedures, methods, or functions. Non-native methods are applications that are only available on Linux or Windows that may be used in combination with PowerShell.

Native Methods:-

Here are a few native methods I would be exploring: 

  • Host RawUI ReadKey Method / $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)
  • Start-Sleep
  • Read-Host
  • Thread Sleep / [System.Threading.Thread]::Sleep()
  • [Console]::ReadKey()

Host RawUI ReadKey / $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)

This method is similar to another method called the Console ReadKey function, but it enables extra parameters to be parsed into the ReadKey method to further modify output and behavior.

$host.UI.RawUI.ReadKey()

Powershell Pause

There are a host of ReadKeyOptions that may be parsed in to improve the RawUI ReadKey method’s functionality.

  • IncludeKeyUp
  • IncludeKeyDown
  • AllowCtrlC
  • NoEcho

This may be utilized as follows: key down events are included, but the text is not echoed out.

$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

Except for cases where the AllowCtrlC option is enabled, this technique will allow the usage of Ctrl-C to exit the command.

Start-Sleep

Start-Sleep is by far the most regularly used pause command. -Seconds and -Milliseconds are two parameters for this command.

Seconds may be used to create a system.double number value, on the other hand, milliseconds accepts solely system.Int32 values. The duration of the pause may be precisely controlled by mixing the two. Sleep is also an alias for Start-Sleep.

Start-Sleep -Seconds 2 -Milliseconds 300

Users couldn’t put a fractional seconds number like 2.4, which is the same amount of time we’re stopping for in the preceding code, before the introduction of PowerShell 6.2.0. Luckily, fractional numbers are now supported in version 6.2.0, so instead of separately writing the milliseconds and seconds, users are now able to state: -Seconds 2.4.

It’s vital to remember that you may use Ctrl-C to exit a Start-Sleep function. This isn’t the case with all approaches!

Read-Host

The techniques listed above show how to suspend execution for a certain length of time. Another technique to attain a Powershell Pause is to ask the user for feedback.

Although this technique requires human activity, it may be highly beneficial to need confirmation before proceeding and perhaps incorporate extra data.

One of the most frequent methods to ask for user input is to utilize Read-Host. The resultant item may be kept for further use in the code or used to suspend execution as needed, by requesting human input.

Read-Host -Prompt "To continue, press any key"

To move the execution along, the user hits the return or enter key once the text has been typed. Doing this, outputs the exact text typed into the terminal without storing the input to a variable.

How To Accomplish a PowerShell Pause [Step-By-Step]

Users can decide to assign the input from Read-Host to a variable if they wish to preserve the resultant text for later use.

$Input = Read-Host -Prompt "To continue, press any key"

In cases when the user wishes to securely read in the input as a string, a simplified process using  Read-Host can be used.

$SecureInput = Read-Host -Prompt "Input your Passphrase" -AsSecureString

Users may exit the Read-Host prompt by pressing Ctrl-C.

Thread Sleep / [System.Threading.Thread]::Sleep()

The Threading function is a less widely used means of activating a PowerShell pause. A running thread may be paused for a specific period of time if a user parses a TimeSpan or System.Int32 value. For example, to effect a PowerShell pause for 2.4 seconds, we use this code:

[System.Threading.Thread]::Sleep(2400)

Users may utilize the Thread Sleep method with a timespan construct by using the following script:

[System.Threading.Thread]::Sleep([TimeSpan]::New(0, 0, 0, 2, 400))

Users may use [System.Threading.Timeout]::InfiniteTimeSpan to suspend a thread forever, but bear in mind that this may freeze the entire process.

Using Thread Sleep approach, unlike its Start-Sleep counterpart, does not enable users to use Ctrl-C to exit a sleep routine. This may be desirable depending on the use case.

It’s also worth noting that thread sleep does not guarantee a certain time. Every thread sleep guarantees that it will be delayed for at least the indicated time. Because thread sleep counts are synchronized with clock ticks, other applications may disrupt this pause function, making the wait time longer.

Thread sleep has its benefits, but these drawbacks make it preferable to utilize one of the other built-in approaches.

Console ReadKey Method

Users may quickly read in modifiers and key commands while performing a PowerShell pause with the [Console]::ReadKey() function. The input commands are repeated to the screen as a System. ConsoleKeyInfo is a kind of object.

This contains the values for KeyChar, Key, and Modifiers, which may be quite handy when looking for specific key combinations.

[Console]::ReadKey()

How To Accomplish a PowerShell Pause [Step-By-Step]

Before continuing on, you may wish to verify for a specific key input. A Do-While loop, such as the one shown below, may easily do this.

Do {
$Key = [Console]::ReadKey($True)

Write-Host $Key.Key
} While ( $Key.Key -NE [ConsoleKey]::Escape )

In this case, using Ctrl-C will not escape the input since we’re seeking for a certain key combination.

Non-Native Methods

We’ll look at a couple of non-native ways to pause script execution in this section. These approaches are meant for integrating non-PowerShell console-specific tools with PowerShell scripts, according to user requirements.

Windows

1. Pause

The pause script is straightforward and will result in a display; “Press any key to continue . . .”  and it will stay that way till a key is touched to restart execution.

cmd /c 'pause'

How To Accomplish a PowerShell Pause [Step-By-Step]

Users may wonder how this script is used, simply paste the cmd /c ‘pause’ command into your script just like any other command to utilize the native capability.

2. Timeout

The timeout command, which is often seen in Windows batch files, enables users to pause for a set amount of seconds while also ignoring any key commands. Even if the waiting period hasn’t expired, a user input will usually restart execution. It is simple to use by just entering the amount of seconds.

# Pause for 4 seconds
timeout /t 4

# sript for a 10 second pause disallowing keystroke breaks
timeout /t 10 /nobreak

# script for an indefinite Pause till a key is pressed
timeout /t -1

Include the timeout command into the script similar to the pause command, and click the enter key to proceed.

Linux

1. Read -P

Linux may pause by utilizing the read program to wait for the enter key to be pressed in order to resume operation. In cases when the enter key is not pressed within the set period, the program will continue to run.

read -p 'Press enter to continue' -t 5

2. Sleep

The sleep command in Linux OS, like the pause command in Windows OS, enables users to specify an indefinite sleep value. The sleep command is different from the pause command in the sense that it offers a few extra arguments that allow for greater sleep duration flexibility.

sleep 2.4s

The sleep command contains alternative suffixes that may be used to specify greater time durations. Here are a few examples:

sleep 4d – Sleep for 4 days
sleep 1h – Sleep for 1 hour
sleep 3m – Sleep for 3 minutes

📗FAQ

How to pause in PowerShell?

The PowerShell Start-Sleep cmdlet can be used to pause a script or command. This cmdlet will halt the script or command for the specified number of seconds.

For instance, you can use the following command to pause for 5 seconds:

Start-Sleep -Seconds 5

The -Milliseconds and -Minutes arguments allow you to select the number of milliseconds or minutes to pause for.

#Pause for 3 minutes
Start-Sleep -Minutes 3

#Pause for 500 milliseconds
Start-Sleep -Milliseconds 500

It’s important to remember that the Start-Sleep cmdlet will halt the entire script or action, not just a single line. Use the sleep alias for the Start-Sleep cmdlet if you only wish to pause one line of code, like in the following example:

sleep 5

To move on to the following line of code, the script or program will halt for 5 seconds.

How do I pause a PowerShell script for 5 seconds?

You may use the Start-Sleep cmdlet and the -Seconds parameter to pause a PowerShell script for 5 seconds as seen in the example below:

Start-Sleep -Seconds 5

The script will stop for 5 seconds before moving to the next line of code.

The script can also be paused for a predetermined number of seconds using the sleep alias for the Start-Sleep cmdlet.

For example:-

sleep 5

Remember that using the Start-Sleep cmdlet or the sleep alias will halt the entire script, not just a particular line of code.

Use the sleep alias followed by the number of seconds to pause for if you only want to pause one line of code:

sleep 5; # Pause for 5 seconds

The script will stop for 5 seconds before moving to the next line of code.

How do I pause a PowerShell script after execution?

The Read-Host cmdlet can be used at the end of a PowerShell script to pause it after it has finished running. This cmdlet waits until the user presses the Enter key before running.

For example:-

Read-Host -Prompt “Press Enter to continue”

To pause the script for a predetermined number of seconds before continuing, you can use the sleep alias for the Start-Sleep cmdlet.

For example:-

sleep 5

To pause the script for a predetermined amount of seconds before continuing, use the Start-Sleep cmdlet in place of the -Seconds parameter.

For example:-

Start-Sleep -Seconds 5

Don’t forget that these techniques will pause the entire script, not just a specific code section. Use the sleep alias followed by the number of seconds to pause if you only want to pause one line of code:

sleep 5;

The script will stop for 5 seconds before moving to the next line of code.

Final Thoughts

Various methods exist to prompt a Powershell Pause for a command-line execution or script. Depending on the user’s requirements, it might be as basic as using a Start-Sleep command or the more complicated input-driven procedure.

When used in conjunction with native commands, PowerShell pause provides optimum script usefulness and flexibility in almost any situation.