PowerShell Start-Sleep Command Explained [9 Examples]

Photo of author

By Victor Ashiedu

Published

Need to delay a PowerShell script for a while? Then, you need the PowerShell Start-Sleep command.

Syntax of Start-Sleep Cmdlet

Here is the syntax of Start-Sleep Cmdlet:

Start-Sleep -Milliseconds <Int32> 
Start-Sleep -Seconds <Int32>  

This cmdlet has two parameters

Milliseconds – use it to specify the time (Int32) in milliseconds. PowerShell will delay for the milliseconds you enter.

For example, if I want to delay my script for 300000 milliseconds (5 minutes), I will run the command below:

Start-Sleep -Milliseconds 300000

Seconds: You can also specify the delay period in seconds. To do this, use the Seconds parameter of the Start-Sleep command.

To continue with the last example, to delay my script for 5 minutes (300 seconds), I will run the command below:

Start-Sleep -Seconds 300

Example 1: Run Start-Sleep with Specified Time

As I explained in the last section, the Start-Sleep command has two syntaxes, as shown below:

Start-Sleep -Milliseconds <Int32>  
Start-Sleep -Seconds <Int32>  

To set PowerShell to delay for 30000 Milliseconds (30 seconds), use any of the commands below:

Start-Sleep -Milliseconds 30000
Start-Sleep -m 30000

Moreover, you can use the Millisecond’s parameter to set sleep to less than 1 second. For example, if you want to delay a PowerShell script for 0.0005 seconds (0.5 Milliseconds), you can use any of the commands below:

Start-Sleep -Milliseconds 0.5
Start-Sleep -Seconds 0.0005

In my third example in this subsection, I want to set PowerShell sleep for 1 hour. The best approach here is to use the Seconds parameter of the Start-Sleep command.

To do that though, you have to convert 1 hour to seconds. You can easily do this by searching convert 1 hour to seconds in google.

The result is 3600 seconds. So, to delay a PowerShell script by 1 hour use the PowerShell Start-Sleep command below:

Start-Sleep -Seconds 3600

As you can see from the screenshot below, the PowerShell command prompt will not be available until the delay (1 hour) is over.

Similarly, you can set PowerShell to sleep for 5 minutes using the command below:

Start-Sleep -Seconds 300
5 minutes equals 300 seconds

Example 2: PowerShell Countdown Function

I wrote a PowerShell function (Start-Count), that counts down or up. The function has 4 parameters:

CountDown: When you specify this parameter, Start-Count counts down from a specified number
CountUp: Alternatively, specifying the CountUp parameter makes Start-Count count upwards from a specified number
CountFrom: Unlike the CountDown and CountUp, this parameter requires an input. Use this to specify the number to count down or up from.
CountTo: Use this parameter to specify the number to count to (down or up)

Follow the steps below to download and use the Start-Count function:

  1. Click download Start-Count.zip
  2. Then, unzip Start-Count.zip. When unzipped, you will see a folder called Start-Count. This folder contains the PowerShell module
  3. Copy the Start-Count folder to your PowerShell Modules folder. This is located in C:\Users\profile_name\Documents\WindowsPowerShell\Modules
  4. Unblock the downloaded module file with the command below:
Unblock-File C:\Users\profile_name\Documents\WindowsPowerShell\Modules\Start-Count\Start-Count.psm1
  1. Finally, open PowerShell and run Start-Count. In the first example, I want to count down from 10 to 0.
Start-Count -CountDown -CountFrom 10 -CountTo 0

In this second command, I am counting up from 5 to 40…

Start-Count -CountUp -CountFrom 5 -CountTo 40

Example 3: Create a Random Time

When you run Start-Sleep, PowerShell counts down from the top of the specified time. For example, if I run Start-Sleep and specify 20 seconds, PowerShell will count down by 1 second.

However, if you want the countdown to be randomized (that is, count down by 2, 5, 6), then you need to combine Start-Sleep and Get-Random.

For example, if I want PowerShell to sleep at intervals between 1 and 10 seconds, I will run the command below:

Start-Sleep -Seconds (1..10 | Get-Random )

Place this command before you run the commands you want to execute at random delay…

Example 4: Create a Pause Until a Certain Time

In some PowerShell scripting scenarios, you may want to set sleep until a certain time. For example, you may want to set sleep for 30 seconds.

To achieve this, you need a Do, Until loop.

In this example, I want PowerShell to sleep until the timer hits 30 seconds.

First, I set the start time and the end time. The start time is the time I want to count from.

To make it easy, I will count from 0.

First of all, I will set where I want to count from….

$CountFrom = 0 #counts from zero.

Then, I will set where I want to count to…

$CountTo = 30 #I want to count to 30

Now, I will use Do, Until loop with Start-Sleep as shown in the script below:

Run each command one at a time
$CountFrom = 0
$CountTo = 30
Do {Write-Host $CountFrom; Start-Sleep 1; $CountFrom++} Until ($CountFrom -gt $CountTo)
I put the whole “Do, Until” script in a single line so I can run it in PowerShell. If you want to run the script in PowerShell ISE, you can write it as shown below:
Do {
Write-Host $CountFrom
Start-Sleep 1
$CountFrom++
} Until ($CountFrom -gt $CountTo)

However, to run the script in PowerShell, run each of the commands below:

$CountFrom = 0
$CountTo = 30
Do {Write-Host $CountFrom; Start-Sleep 1; $CountFrom++} Until ($CountFrom -gt $CountTo)

Example 5: Add Pause After or Before a Command

This is a very simple example. If you want to add a delay after a PowerShell command, add the Start-Sleep command after the PowerShell command.

For example, to add 5 minutes wait after running Get-Process, use the command below:

Get-Process; Start-Sleep -Seconds 300

As shown in the screenshot below, when the Get-Process command completes, PowerShell does not return to its prompt. This indicates that the 5 minutes (300 seconds) delay is in place.

On the opposite side of the above example, you can also use PowerShell sleep to add a delay then run a command.

This time, instead of adding Start-Sleep after the command, we add it before the command…

Start-Sleep -Seconds 300; Get-Process

This time around, the delay will kick in before the command runs.

Example 6: Use PowerShell Sleep to Retry a Script

In trying to find a solution to this, I found an existing script submitted by a Stackoverflow.com contributor (Ansgar Wiechers).

Ansgar created the function below. He called it Retry-Command. I changed the function to Redo-Command so as to use a PowerShell approved verb.

Other than that, I give full credit to Ansgar Wiechers. Here is the full script…

function Redo-Command {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [scriptblock]$ScriptBlock,

        [Parameter(Position=1, Mandatory=$false)]
        [int]$Maximum = 5,

        [Parameter(Position=2, Mandatory=$false)]
        [int]$Delay = 100
    )

    Begin {
        $cnt = 0
    }

    Process {
        do {
            $cnt++
            try {
                $ScriptBlock.Invoke()
                return
            } catch {
                Write-Error $_.Exception.InnerException.Message -ErrorAction Continue
                Start-Sleep -Milliseconds $Delay
            }
        } while ($cnt -lt $Maximum)

        # Throw an error after $Maximum unsuccessful invocations. Doesn't need
        # a condition, since the function returns upon successful invocation.
        throw 'Execution failed.'
    }
}

Well, I also uploaded the script for our readers to download and use. To download and use the function, follow the steps below:

  1. Click download Redo-Command.zip. Then, unzip the downloaded zip file.
  2. Copy the unzipped folder, Redo-Command to c:\users\Documents\WindowsPowerShell\Modules
  3. Then, open PowerShell and run the command below – the command unlocks the file. This stops PowerShell constantly warning you that the file was downloaded from the internet
Unblock-File c:\users\Documents\WindowsPowerShell\Modules
  1. Finally, to use the PowerShell function Sleep to retry a script, run a command like the one below:
Redo-Command -ScriptBlock {
    # add your command here
}

The default retry is 5 times. However, if you want to add a custom retry, use the Maximum parameter as shown below…

Redo-Command -ScriptBlock {
# add your command here
} -Maximum 8

In the last command, you get a retry 8 times before an error is returned.

Example 7: Pause a Script Until a File Exists

To put a PowerShell script to sleep until a file exists, you need to use Test-Path and Start-Sleep in a “While” loop.

Here is the general syntax of the PowerShell “While” loop you need:

While (check if file exists) {delay for a while and check again}

To give an example, I will check if a file called eventlog.txt in drive D exists. The script will not proceed until the file is available.

Here is the script…

while (!(Test-Path "d:\eventlog.txt")) { Start-Sleep 10 }

The Test-Path command checks if a file exists. If the file exists, Test-Path returns True.

On the contrary, if the file does not exist, Test-Path returns False. By adding “!” before Test-Path, I reversed the result.

So, the result in the while loop is True if the file does not exist.

I essence, what the command says is this: if “Test-Path “d:\eventlog.txt”” equals False (The file does NOT exist), return True for the “while” loop. Moreover, as far as the “while” condition is True, execute the command “Start-Sleep 10” (delays for 10 seconds).

Then, return to the condition part of the “while” loop and check if the file exists. If not, delay for another 10 seconds. This loop will continue until the file exists – then, the loop will break and PowerShell will resume.

To test this script, I will run it first (without the file, d:\eventlog.txt)

To break the loop, I will create the file. Once I create the file, the “while” loop will break and PowerShell will continue:

Example 8: Add a Pause Forever Until Ctrl + C

If you are running a command that you do not want to break until you press Ctrl + C, you need the “while” loop.

For example, to run the PowerShell command – Get-EventLog -LogName Application – forever (continuously, until you press Ctrl + C), use the command below:

while ($true) {Get-EventLog -LogName Application}

What the command does is this: as far as the command in the {} part of the “while” loop is true, continue running.

Example 9: Pause Until a Running Process is Finished

This example is the direct opposite of the last example. In the last example, I kept a process running continuously.

However, in this example, I want PowerShell to sleep until the process is completed. Once the process finishes, the sleep terminates.

Like the previous example, a “while” loop will do the job. However, the way the “while” loop is configured is different.

This time, I put the command in the () block of the “while” loop. However, I need to add “!” before the command.

Here is my example…

while (!(Get-EventLog -LogName Application)) { Start-Sleep 5 }

This command says to PowerShell, “while (Get-EventLog -LogName Application) is true”, make PowerShell sleep for 5 seconds. After the sleep, PowerShell will check whether the command (Get-EventLog -LogName Application) is still running.

If it is still running, start sleep for another 5 seconds. This loop will continue until the command completes…

Conclusion

I have used the start-sleep command in so many scripts that I have lost count! If you’re going to code like a pro, you must know your way around this command.

I am confident that after going through this guide, you have been equipped with the knowledge you need to start coding with the Start-sleep command.

If my assumption is accurate, kindly let me know by responding to the “Was this page helpful?” question below.

Finally, you may find our other PowerShell guides helpful. To read more insightful PowerShell guides, visit our PowerShell & CMD Explained page.

One more thing before you go, if you want to learn PowerShell, you may want to bookmark our PowerShell Tutorials page.

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

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  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