Powershell Sleep – How to Pause a Script

Clear2all Professional Blog new

Powershell Sleep or Pause – How to Pause or sleep a Script?

You may need to pause your PowerShell script for a few seconds from time to time. When you use a do while loop to check if a server is back online, for example. The PowerShell Start Sleep cmdlet can be used to accomplish this. We can put the script to sleep for a few seconds using this command.
In this article, I’ll show you how to utilize the PowerShell Sleep command with a handful of examples.
Using the Start Sleep cmdlet in PowerShell

The start-sleep cmdlet in PowerShell is actually rather simple to utilize to pause your script. The sleep time can be set in seconds (the default) or milliseconds.

How to pause sleep your PowerShell script for 10 seconds?

# To Pause for 10 seconds per loop
Do {
    Start-Sleep -s 10
while ($condition -eq $true)

Start-Sleep 10 is another option for putting the script to sleep for 10 seconds. However, it is preferable to use the -s or -seconds parameter to make your script more readable.

How to pause sleep your Powershell for Milliseconds?

The other option except seconds. This allows you to have your script wait for only a few seconds.

# Pause for 0.1 second per loop
Do {
Start-Sleep -Milliseconds 100
while ($condition -eq $true)

The start-sleep cmdlet is most commonly used in a PowerShell loop. The sleep cmdlet, on the other hand, can be used anywhere in your script. The only issue is that you’re most likely guessing how long you should wait.
Instead of halting your script for 30 seconds and hope that the other “thing” you’re waiting for is finished, use a do-while loop to check for a condition, feedback, or process state.

How to Pause sleep Powershell Sleep with a Progressbar?

When you use the start-sleep cmdlet to suspend a PowerShell script, you won’t see anything in the console. You may add a progress bar to your sleep command to provide visual feedback to the user.

Function Sleep-withstatus($inputseconds) 
{ $sleep = 0; Do { $pause = [math]::Round(100 - (($inputseconds - $sleep) / $inputseconds * 100));
Write-Progress -Activity "Waiting..." -Status "$pause% Complete:" -SecondsRemaining ($inputseconds - $sleep) -PercentComplete $pause; [System.Threading.Thread]::Sleep(500) 
$sleep++; } While($sleep -lt $inputseconds); }
Sleep-withstatus 10

Powershell Sleep How to Pause a Script

Leave a Reply

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