How To Sleep PowerShell with Start-Sleep Command-let Tutorial with Examples?


PowerShell is not just a shell where it can provide programmatic features. We can use Start-Sleep command-let in order to suspend the script or activity for specified period of time.

Syntax

Start-Sleep has very simple syntax where we will just provide the options which is used to specify seconds or milliseconds and the time we want to sleep.

Start-Sleep OPTION TIME

Sleep As Seconds

We will start with the sleeping or suspending in seconds. We will use -s option with the time which is 5 seconds in this example.

PS> Start-Sleep -s 5

Sleep For 10 Seconds

In this example we will sleep the PowerShell for 10 seconds.

PS> Start-Sleep -s 10

Sleep For 60 Seconds

In this example we will sleep the PowerShell for 60 seconds.

PS> Start-Sleep -s 60

Sleep For Milliseconds

In some cases we may need more precises values to sleep or suspend the execution. We can use milliseconds as time value. We will use -m in order to change time to the milliseconds. In this example we will sleep for 50 milliseconds.

PS> Start-Sleep -m 50

Sleep Until User Input

We have all ready learned the usage of Start-Sleep to suspend specified time. We can also use ReadKey function in order to suspend execution of the script or shell up to a user input. The user input is just a keystroke which will start the execution again.

PS> $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | out-null
Sleep Until User Input
Sleep Until User Input

If we do not want to print  input to the console we can add | out-null to the end of the ReadKey() function.

Start-Sleep As Alias of sleep Command

Start-Sleep name refers to the PowerShell explicitly. We can use more simple alias of Start-Sleep named sleep. sleep will use Start-Sleep with the same options and argument. In this example we will sleep for 3 seconds with -s option.

PS> sleep -s 3

Start-Sleep Interactive Usage

We can also use Star-Sleep command-let in a interactive way in PowerShell. We will just call the Start-Sleep like below and then input the parameter.

PS> Start-Sleep
Start-Sleep Interactive Usage
Start-Sleep Interactive Usage

Sleep In While Loop

Start-Sleep can be used in different cases but one of the most popular one will be a loop. For and While loops are good use cases for Start-Sleep. In this example we will sleep for 5 seconds when the counter can be divided into 5.

$val=0


while($val -ne 10)
{
  $val++
  Write-Host $val

  if($val%5 -eq 0)
    {
      Start-Sleep -s 5
    }
}
Sleep In While Loop
Sleep In While Loop

LEARN MORE  Python Script Change Mac Address Periodically

Leave a Comment