How to Pause a PowerShell Script

Photo of author

By Victor Ashiedu

Published

Do you want to learn different ways to pause (suspend) a PowerShell script? This guide teaches you different methods to temporarily stop a PowerShell from executing.

Why you may Need to Pause a PowerShell Script?

I wrote a script some years ago that provisioned Office 365 mailboxes for on-prem AD users. After creating an office 365 mailbox for a user, the script assigns a license before proceeding to the next tasks.

However, after creating the mailbox and assigning a license, I realized that Office 365 needed some time to provision the mailbox fully. At this point, I need to add a 3 minutes delay.

For this specific scenario, I used the command…

Start-Sleep -Seconds 180

This is one real-scripting reason you may want to add a pause to a script. Most times, you may need to pause a script if the next task execution requires input from the current task.

However, the current task needs more time to complete. Some other times, your script may require input from a person.

For example, you may need the person that initiated the script to respond to a message on the console or enter an input the script requires to continue.

As you will read in the next section, there are other methods to add a temporal wait to a PowerShell script. The method you decide to use depends on the scripting scenario.

Different Ways to Pause a PowerShell Script

As I mentioned in the last section, PowerShell offers different methods to add a wait to an executing script. In the following subsections, I examine 6 of them.

Option 1: Suspend a PowerShell Script with the “Pause” Command

The “Pause” command is a Command Prompt command. As you would expect, this command works in PowerShell.

If you type pause and press enter key, PowerShell or CMD suspends the processing of any further command and displays the message…

Press any key to continue . . .
Temporarily Stop PowerShell With The "Pause" Command

If you want to suspend executing your script until the user presses any key, use this method. However, using “pause” has one limitation – it doesn’t have any switches or parameters.

Another important thing to note about the “Pause” command is its somewhat misleading message – Press any key to continue . . .

Even though the message says, “Press any key…” it does not accept some keyboard inputs. For example, if you press the following keys – Ctrl, Shift, Windows, Alt – the “pause” command will not respond.

Option 2: Pause a PowerShell Script with the Start-Sleep Command

This is the most versatile method of suspending a PowerShell script from executing. The Start-Sleep command gives you multiple options to pause a script.

For example, with the Start-Sleep command, you can delay a script in Milliseconds, 1 Second (Or Less), Minutes, Or For 1 Hour. In addition to that, you can also use this command to generate Random Time, wait Until a Certain Time, and do much more.

To learn more ways to use start-sleep to suspend the execution of a PowerShell script, read my Powershell Sleep Examples.

Option 3: Suspend a PowerShell Script with the $host.UI.RawUI.ReadKey() Method

The $host automatic variable has a Property called UI. If you dig further, the $host.UI property has a RawUI property.

Furthermore, $host.UI.RawUI has the ReadKey() Method. You can use the $host.UI.RawUI.ReadKey() Method to pause a PowerShell script.

The beauty of using this method to pause your script is that it gives you loads of options. To see how this works, open PowerShell and run the command below.

$host.UI.RawUI.ReadKey()

PowerShell will suspend all executions until you press a key. Now, press the = key on your keyboard and see some magic happen.

pause A PowerShell Script With The $host.UI.RawUI.ReadKey() Method

When you press the = key, PowerShell resumes. However, if you look closely, you notice that the command returned = in its “Character” column.

This means that I can make the last command into a tiny script that executes only on a specific keystroke. For example, if I want to execute a part of a script when the user presses 1 and another when the user presses 2, I will use the script below.

$keystroke = $host.UI.RawUI.ReadKey()
If ($keystroke.Character -eq "1") {write-host "user pressed 1" }

The limitation of this method of suspending a PowerShell script is only limited by your imagination!

Option 4: Pause a PowerShell Script with the Read-Host Command

The Read-Host command is your best option if you need a user to enter input. The command has two parameters that you’ll find useful.

Firstly, you can use the -Prompt parameter to request for input from a user. For example, you can run the command below to request the age of the user…

Read-Host -Prompt "Enter your age"

When you run the command, PowerShell will prompt for input…

Pause A PowerShell Script With The Read-Host Command

The user will type her age, then press the Enter key. You can save the input in a variable and use it to perform a task in your script.

Earlier, I mentioned that the Read-Host command has two important parameters. I have already discussed the -Prompt parameter.

The second parameter of the Read-Host command you’ll find useful is the -AsSecureString parameter. When you write a script, you can use this to save a password in a variable securely.

Then, you can use the password as you deem fit. Here is a sample command

$Password = Read-Host -Prompt "Enter a password" -AsSecureString

When you run the commands, PowerShell will prompt you to enter a password. PowerShell will not display the password you entered.

Pause A PowerShell Script With The Read-Host Command

Option 5: Suspend a PowerShell Script with the Start-Proces -Wait Command

The Start-Proces command has a -Wait parameter you can use to pause a script in PowerShell. When you run the Start-Proces command with the -Wait parameter, PowerShell will not proceed to the next task until the current command has been completed.

This is useful if the next command in your script needs the result of the current command to work.

When I was writing this subsection, I wondered about the command to use for my example. Then, I remembered the popular DISM command…

DISM.exe /Online /Cleanup-Image /Restorehealth

If you run this command, it takes some time to complete. So, if you run it in a PowerShell script, to ensure that your script waits for the command to complete, it is better to call the command with the Start-Proces command.

Here is the sample command…

Start-Process -FilePath "DISM.exe" -ArgumentList @("/Online", "/Cleanup-Image", "/Restorehealth") -NoNewWindow -Wait
The -NoNewWindow parameter forces Start-Process to start the DISM command in the same PowerShell console window. Without this parameter, Start-Process opens DISM in a new CMD console window. Similarly, the -Wait parameter forces PowerShell to wait until the command is completed. In addition to waiting, it also ensures that PowerShell returns to the prompt when the command is completed. If you exclude the -Wait parameter, PowerShell will wait for keyboard input before it proceeds to the next command.

When I run the command, PowerShell waits for the command to complete before returning to its prompt.

When the DISM command is completed, PowerShell returns to the prompt, ready to execute the next command. If you do not include the -Wait parameter, PowerShell will wait for keyboard input before it proceeds to the next command.

Pause A PowerShell Script With The [System.Threading.Thread]::Sleep() .NET Method

Another method to suspend a PowerShell script is the [System.Threading.Thread]::Sleep() .NET method. The Sleep() method supports System.Int32 or a TimeSpan value.

Here is a sample command that uses the System.Int32 value. The command below pauses the script for 3.6 seconds.

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

Option 6: Pause a PowerShell Script with the [System.Console]::ReadKey() Method

This is another interesting method to suspend a PowerShell script. The basic syntax of this command is…

[System.Console]::ReadKey()

When you run the command, it suspends further actions until you press a key. Then, the command registers the key you pressed.

In this example, I pressed key 8. As you can see in the second screenshot below, the command registers the key I pressed.

Pause A PowerShell Script With The [System.Console]::ReadKey() Method

I can use this information to customize my script. For example, I may want my script to perform a specific action if the user presses one key and another action on a different key press.

Moving on, you would have noticed that the basic syntax of the command displays multiple pieces of information. However, if I want it to display just my keypress, I’ll modify it as shown below.

[void][System.Console]::ReadKey($FALSE)

Unlike the original command that displays additional information, the last command just displays the key I pressed on my keyboard.

Suspend A PowerShell Script With The “TimeOut” Command

The final method to pause a PowerShell script I want to share with you is the “TimeOut” command. This is a CMD command, but it works in PowerShell.

The syntax of this command is…

TimeOut /Options

The command has some useful options you can use to suspend your script. At the basic level, you can pause a PowerShell script for a specified time using the /T option.

If you use this option, PowerShell will pause for the specified time. However, you can also break the pause by pressing any key on your keyboard.

Here is an example that creates a 30 seconds pause…

TimeOut /T 30

When you run the command, it will start counting down from the number you specified. Then, when it reaches zero – see the second screenshot below – PowerShell will continue.

Suspend A PowerShell Script With The "TimeOut" Command

As I mentioned earlier, running the TimeOut with the /T option starts a countdown, but you can also break the pause by pressing any key on the keyboard. However, to disable interrupting the timeout with a keypress, specify the /NOBREAK option.

TimeOut /T 30 /NOBREAK

Running the command above pauses the PowerShell console for the specified time (in seconds), and you cannot interrupt the pause by pressing any key.

PowerShell Pause Examples

So far, I have discussed 8 methods of pausing a PowerShell script. In this section, I will share 7 examples and practical ways to suspend execution in PowerShell.

Example 1: Pause a PowerShell Script in for x Seconds

When I discussed the different methods to create a pause in PowerShell, I gave some examples. In some of those examples, I shared how you can suspend execution in PowerShell for specific seconds.

The easiest way to do this is to use the Start-Sleep command. For example, to pause a PowerShell script for 1 minute, I’ll run the command below.

Start-Sleep -Seconds 60

In addition to using the Start-Sleep command, you can also use any of the following commands to pause a PowerShell script for 60 seconds.

TimeOut /T 60
[System.Threading.Thread]::Sleep(60000)

Example 2: Pause a PowerShell Script and Wait for Input

The best method to pause a PowerShell script execution while you wait for input is to use the Read-Host command.

Additionally, you can also use the $host.UI.RawUI.ReadKey() and the [System.Threading.Thread]::Sleep() methods.

To see applications of how to use these methods to pause a Script and wait for keyboard input, see the previous section.

Example 3: Pause a PowerShell Script Until Keypress

This example is similar to the last command, but it is a bit more simplified. The easiest way to create a pause until a keypress is to use the “pause” command.

Alternatively, you can use the “Timeout” command with the /T option. When you specify -1 as the /T option, the “Timeout” command will wait indefinitely until a keypress.

Timeout /T -1

So, running “Timeout /T -1” is the same as running “pause.” Both commands pause PowerShell indefinitely until a keypress.

Example 4: Pause a PowerShell Script Between Commands

If you need to add an automatic timed-out pause between two PowerShell commands, construct your script with the following logic:

  1. Run the first command
  2. Then, add the automatic timed-out pause with either the Start-Sleep or the TimeOut commands.
  3. Finally, run the second command.

Alternatively, you can add a pause that waits for the first command to finish before the second command runs.

To illustrate the automatic time-out example with the script below.

$start = Get-Date
Start-Sleep -Seconds 30
$end = Get-Date
$elapsed = $end - $start
Write-Host "$elapsed has passed since the first command"

The first line of the script saves the current timestamp in the $start variable. Then, in line 2, I used Start-Sleep to initiate a 30 seconds pause before the next command ran.

After the pause elapses, I take another timestamp and save the result in the $end variable. Then, in line 4, I calculate the total time from when I ran the first Get-Date command and when I ran the second Get-Date command.

Finally, I display this time difference on the console using the Write-Host command in line 5. Here is the result of the command in PowerShell ISE.

How To PowerShell Pause A PowerShell Script Between Commands

On the other hand, to illustrate the pause that waits for the first command to complete before running the second command, I will use the script below.

Start-Process -FilePath "ping.exe" -ArgumentList @("/n 30", "/a 54.239.28.85") -NoNewWindow -Wait
Write-Host "Ping is completed"

Example 5: Pause a PowerShell Script on Error

To pause a PowerShell script on error, you need to introduce the ErrorAction parameter. You can use this parameter to determine how PowerShell responds to non-terminating errors.

For example, I’ll ping a non-existing website, rest.com, and use the ErrorAction parameter of Test-Connection with the Stop option. Here is the command…

Test-Connection rest.com -ErrorAction Stop

The command will display an error message and stop PowerShell from executing any command following this command.

Obviously, the way PowerShell displays the error message is not nice. To catch the error messages and display the actual error message, wrap the command in a Try-catch statement.

Try {
 Test-Connection rest.com -ErrorAction Stop
 }
 Catch {
 $error[0].Exception.Message

}

The above command will handle the error better and display the actual error message. The error I highlighted in the screenshot below was produced by the command in the catch element of the Try-catch statement.

Example 6: Pause a PowerShell Script with a Message

In a previous example, I discussed how to use the Read-Host command to pause a script and display a specific message. This example displays the message, “Press any key to continue.”

Read-Host "Press any key to continue"

However, if you want to display a message while pausing a script for a specified time, you can use the “TimeOut” command with the /T option.

TimeOut /T 60 /NOBREAK

Better, you can use the Write-Host command to display a message, then use the Start-Sleep command to suspend the PowerShell script from executing.

Write-Host "The script has been paused for 30 seconds. Please wait"; Start-Sleep -Seconds 30
I used ; to separate both commands since I am running them on a single line.

Example 7: Pause a PowerShell Script at the End of Script or After Execution

You can use the Start-Sleep command to create a pause at the end of a script or after the script execution.

However, how you implement it depends on the situation. The most basic command of Start-Sleep will pause the script for the specified time.

For example, if I want to add a 30 seconds pause at the end of a PowerShell script, I’ll use the command below.

Start-Sleep -Seconds 30

In other situations, you may need to add a pause at the end of a script, but you may require user input to either end the script or continue executing another part of the script.

If you need to add a pause that requires user input, use the Read-Host command. For example, the following command will pause the script until a user responds.

Read-Host "Do you want to continue the script? [Y] continue the script [N]  terminate the script"

Frequently Asked Questions

1. How do you wait 5 seconds in PowerShell?

You can use one of the commands below to wait 5 seconds in PowerShell:

Start-Sleep -Seconds 5
TimeOut /T 5

2. Is there a wait command in PowerShell?

Yes, there are some commands that have the “Wait” verb in them. To list all the commands with the “Wait” verb, run the command below:

Get-Command wait

Furthermore, some PowerShell cmdlets have the -wait parameter. To see all PowerShell cmdlets that have the -wait parameter, run the command below:

Get-Command -ParameterName wait

3. How do I set timeout in PowerShell?

PowerShell can run the Timeout command with the /T switch to specify how long the timeout will last. So, to set timeout in PowerShell, run the command below:

Timeout /T 30

Change the 30 to the time (in seconds) you want to set the Timeout.

4. How do I add a sleep command in PowerShell?

To add a sleep command in PowerShell, use the Start-Sleep command, and specify the -Seconds or -Milliseconds parameters.

For example, to add a 50 seconds sleep in PowerShell, run the command below:

Start-Sleep -Seconds 50

5. How do you break a loop in PowerShell?

Use the break keyword to break a loop in PowerShell

Conclusion

There are numerous reasons people may want to add a pause in a PowerShell script. From waiting for a command to complete to requesting for input, pausing is essential to scripting in PowerShell.

In this guide, I discussed various reasons you may want to pause a script. Then, I shared 8 methods to suspend a PowerShell script.

After that, you read seven examples and applications of pausing in PowerShell.

No matter your reason for wanting to suspend a PowerShell script from executing, I hope you found this guide helpful! If you did, click on “Yes” beside the “Was this page helpful” question below.

You may also express your thoughts and opinions by using the “Leave a Comment” form at the bottom of this page.

Finally, to improve your PowerShell knowledge further, read our other PowerShell topics by visiting our Windows PowerShell How-To Guides page. Alternatively, visit our PowerShell Explained page.

We go the extra mile to deliver the highest quality content for our readers. Read our Content Writing, Content Review, and Anti-Plagiarism policies to learn more.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

If this article does not meet your expectations, kindly let us know. We have various ways you can get in touch with us:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment

Send this to a friend