The Underappreciated PowerShell Cmdlet Start-Sleep

The Underappreciated PowerShell Cmdlet Start-Sleep

Use of the Start-Sleep Cycle

Because the Start-Sleep cmdlet only requires two parameters, it's quite simple to use. Let's imagine I need to halt my script while I wait for a different environmental process to complete. That procedure takes about 10 seconds, and I need to make sure my script doesn't continue to run before the external event is completed.

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 of a Situation

A while loop is one of the most typical places to use the Start-Sleep cmdlet. A while loop is a PowerShell component that runs code while something else is going on. Waiting for something else to happen is one of the best uses of a while loop. Instead of guessing how long a process will take and calling this cmdlet directly, you can use this cmdlet.

It may take some time for a file to appear in a folder, for example. Perhaps another program dropped the file. After the file has been placed 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 occurred. Technically, we don’t need Start-Sleep to do this, but if not used, this code could cripple your computer. It would be up to PowerShell to determine how fast it could check for this file continuously!

This file does not need to be checked every .0455ms. The check should be slowed down and performed only 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

}"