A PowerShell script is not just a shell that provides programmatic capabilities. Start-Sleep can be used to suspend a script or activity for a specified amount of time.
Using Start-Sleep is very simple, we just need to specify whether we want to sleep in seconds or milliseconds, along with the time we want.
"Start-Sleep OPTION TIME"
We will begin by sleeping or suspending in seconds. The time in this example is 5 seconds, so we'll use -s option.
"PS> Start-Sleep -s 5"
We will sleep PowerShell for 10 seconds in this example.
"PS> Start-Sleep -s 10"
We will sleep PowerShell for 60 seconds in this example.
"PS> Start-Sleep -s 60"
Occasionally, we may need more precise values to sleep or suspend the execution. Milliseconds are a good time value. Using -m, we can change the time to milliseconds. We will sleep for 50 milliseconds in this example.
"PS> Start-Sleep -m 50"
We have already learned how to use Start-Sleep to suspend a specified time. We can also suspend script execution using the ReadKey function. By pressing a key, the execution will start again.
"PS> $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | out-null"
Sleep Until User Input
If we do not want to print input to the console, we can add out-null at the end of the ReadKey() function.
PowerShell is explicitly referred to by the Start-Sleep name. Sleep is a simpler alias of Start-Sleep. As with Start-Sleep, sleep uses the same options and arguments. Using the -s option, we will sleep for 3 seconds.
"PS> sleep -s 3"
In PowerShell, we can also use the Star-Sleep command-let interactively. The Start-Sleep function will be called as shown below.
"PS> Start-Sleep"
Start-Sleep Interactive Usage
A loop is the most popular way to use Start-Sleep. For and While loops are good uses of Start-Sleep. When the counter can be divided into 5, we will sleep for 5 seconds.
"$val=0
while($val -ne 10)
{
$val++
Write-Host $val
if($val%5 -eq 0)
{
Start-Sleep -s 5
}
}"