Powershell Sleep – Pause your Script

Sometimes you will need to pause your PowerShell script for a couple of seconds. For example when you are using a do while loop to check if a server is back online. To do this we can use the PowerShell Start Sleep cmdlet. With this command, we can let the script sleep for a couple of seconds.

In this article, I am going to give you a couple of examples of how you can use the PowerShell Sleep cmd.

Using the PowerShell Start Sleep cmdlet

The start-sleep cmdlet in PowerShell to pause your script is actually pretty straightforward to use. You can define the sleep time in seconds (default) or milliseconds. To let your PowerShell script pause for 5 seconds you can do the following:

# Pause for 5 seconds per loop
Do {
    # Do stuff
    # Sleep 5 seconds
    Start-Sleep -s 5
}
while ($condition -eq $true)

You can also write Start-Sleep 5 to let the script sleep for 5 seconds. But for the readability of your script is it better to define the -s or -seconds parameter.

The only other parameter besides seconds is milliseconds. This allows you to let your script wait for only a short amount of time.

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

The most common place to use the start-sleep cmdlet is in a PowerShell loop. But you can use the sleep cmdlet anywhere in your script. The only problem with that is that you are probably guessing how long you should wait.

The best is to use a do-while loop and check for a condition, feedback, or process state, instead of pausing your script for 30 seconds and hoping that the other “thing” that you are waiting for is finished.

PowerShell Sleep with Progressbar

When you pause a PowerShell script with the start-sleep cmdlet then you won’t see anything happening in the console. To give the user some visual feedback you could add a progress bar to your sleep command.

powershell sleep

We are using the Write-Progress cmdlet for this and calculate the percentage and time remaining in a do-while loop.

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

Sleep-Progress 7

Get more stuff like this

IT, Office365, Smart Home, PowerShell and Blogging Tips

I hate spam to, so you can unsubscribe at any time.

Leave a Comment

0 Shares
Tweet
Pin
Share
Share