Master Start-Sleep: Pause Scripts Efficiently

Published:17 June 2019 - 1 min. read

The PowerShell Start-Sleep cmdlet or the sleep alias is a simple cmdlet with a single purpose; to pause a script. When executed, in the PowerShell console, a script executed by the console or in the PowerShell ISE, the cmdlet pauses merely a script or module in the PowerShell session from running until the required time in seconds or milliseconds have elapsed.

This cmdlet is simple yet can be applied in a few different ways that will allow us scripters to greate well-written scripts.

Start-Sleep Usage

Using the Start-Sleep cmdlet is extremely easy since, after all, it only has two parameters! Let’s say I want to pause my script because I’m waiting for some other environmental process to run. That process takes around 10 seconds, and I need to be sure that my script doesn’t keep running before that external event is done.

To pause the script for 10 seconds, I’d just use Start-Sleep -Second 10. If I want to get anal about things, I could also specify the time in milliseconds as Start-Sleep -Milliseconds 10000.

Example Context

One of the most common uses of this Start-Sleep cmdlet is inside of a while loop. A while loop is a construct in PowerShell that executes code while something else is happening. One of the best uses of a while loop is to wait for something else to happen. Rather than just guessing how long a process is going to take and running this cmdlet directly.

For example, perhaps you need to wait for a file to show up in a folder. Maybe that file is dropped there by some other software. Once the file is in the folder, you need to run some code against it. This example is an excellent example of using a while loop and Start-Sleep.

In the example below, my code is waiting for the C:\File.txt file to show up. If this were in a script, it would pause the script until this event happened. Technically, we don’t need Start-Sleep to do this, but if not used, this code could cripple your computer. The speed at which it could continually check for this file would be up to PowerShell!

We don’t need to check this file every .0455ms. Instead, we should slow that check down and only perform the test every five seconds. Slowing a while loop down is an excellent use of the Start-Sleep command.

$filePath = 'C:\File.txt'
while (-not (Test-Path -Path $filePath)) {
    ## Wait a specific interval
    Start-Sleep -Seconds 5
}

For an example of using this cmdlet with a nice progress bar, check this out.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!