The Start-Sleep cmdlet is used in PowerShell scripts when you need to pause the execution of code for a few seconds or minutes. This command is used in scenarios in which you want to wait for an operation to complete, for a specific event to occur, or to pause while waiting for user input.
By default, the sleep time is specified in seconds or milliseconds. In order to pause a PowerShell script for 10 seconds, use the command:
Start-Sleep 10
It is possible to specify explicitly that the delay should be in seconds:
Write-Host "Pausing for 10 seconds..." Start-Sleep -Seconds 10 Write-Host "Resuming execution..."
Sleep is an alias of the main Start-Sleep command, so you can use the shorter command in your scripts. For example, let’s set the duration of the delay in milliseconds:
Sleep -Milliseconds 500
Start-Sleep does not allow you to specify a delay in minutes or hours, so you can use the following syntax to get a minute or hour delay in your script:
$PauseMinutes = 2 Sleep -Second ($PauseMinutes * 60)
or:
$PauseHours = 2 Sleep -Second ($PauseHours * 60 * 60)
Start-Sleep is often used in infinite loops where the script needs to wait for a specific change or event. This construction allows you to save computing resources (CPU time, RAM, etc.) by adding a pause between checks to the script..
Do { # add here your code # Sleep 5 seconds Start-Sleep -s 5 } while ((Test-Path -Path $filePath) -eq $false)
You must press Ctrl + C to interrupt execution of the Start-Sleep command in the console or script. In this case, the next command in your session or script will be executed.
When you use the start-sleep cmdlet to pause a PowerShell script, you see nothing in the console. You can use the Write-Progress cmdlet to display a script’s pause status as a progress bar.
$PauseInSeconds=20 $sec=0 while ($sec -lt $PauseInSeconds) { $percent= [math]::Round(($sec/$PauseInSeconds)*100) Write-Progress -Activity "Waiting $percent%" -PercentComplete $percent -SecondsRemaining ($PauseInSeconds - $sec) Start-Sleep -Milliseconds 1000 $sec++ }
Such a script will show the number of seconds the script will pause and the current overall progress.
Hint. On the command line, you can visualize the countdown time remaining until the end of the pause in the script by using the command TIMEOUT /T.
For example:
TIMEOUT /T (20)