Many of you know the “timeout” command we used when we created Windows Batch scripts. This pauses/waits/sleeps the script for a specific amount of time. In PowerShell, we can use the Start-Sleep cmdlet to suspend/pause/sleep/wait the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to be completed or pausing before repeating an operation.
To sleep a PowerShell script for 5 seconds, you can run the following command
Start-Sleep -Seconds 5
You can also use the -milliseconds parameter to specify how long the resource sleeps in milliseconds.
Start-Sleep -Milliseconds 25
There are also aliases for the parameter such as -s and -ms if you don’t want to type out the full name. If you want to learn more about the Start-Sleep cmdlet, check out Microsoft Docs.
Another option is to use the Read-Host cmdlet. This is waiting until the user provides any input before the script continues and with that allows you to easily pause a PowerShell script until a key press, for example:
Read-Host -Prompt "Press any key to continue..."
Usually this is used to get some input from an user, which can be reused like:
$InputFromUser = Read-Host -Prompt "Get me some input..."
To learn more about what you can do with the Read-Host cmdlet, check out Microsoft Docs.
And I think many of you know, needless to say, that if you can avoid waits in a script, that’s a good thing. 😉
I hope that quick PowerShell post gives you an overview of how to add a sleep/wait/pause in a PowerShell Script. If you have any questions, feel free to leave a comment. If you want to know more about how you can install and update to PowerShell 7, check out my blog post, you can also learn what is new in PowerShell 7 right here.
You can also learn about PowerShell remoting between Windows, Linux, and macOS using PowerShell remoting over SSH.
Tags: command line, Pause, PowerShell, Powershell Script, script, Sleep, Start-Sleep, Suspend, timeout, Wait Last modified: June 27, 2022
My E-Mail adress will be published to u!!!
I have a .ps1 script file to refresh data in multiple excel files, which worked well… until recently.
The script file used ( | Out-Null ) to force the command to complete before continuing with the rest of the script.
Ex: $workbook.RefreshAll() | Out-Null
.. do more tasks
How can I have this wait for the RefreshAll() to complete before moving on?
Thank you!!
You can just use :
Sleep 10
OR
Function sleep-for ($sec) {
$a=0;
Do{
$b=[math]::Round(100-(($sec-$a)-$sec*100))
Write-progress -activity “waiting..” -status “$b% about to finish::” -secondsRemaining ($sec – $a) -percentComplete $b; $a++;
}
}
#call function
Sleep-for -sec 10
So how would you “pause” an action?
Read-Host can work as a pause function also using “Pause” works as well.