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

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

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.

Syntax

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"

Sleep As Seconds

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"

Sleep For 10 Seconds

We will sleep PowerShell for 10 seconds in this example.

"PS> Start-Sleep -s 10"

Sleep For 60 Seconds

We will sleep PowerShell for 60 seconds in this example.

"PS> Start-Sleep -s 60"

Sleep For Milliseconds

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"

Sleep Until User Input

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.

Sleep Command As Alias For Start-Sleep

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"

Interactive Use of Start-Sleep

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

Sleep In While Loop

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

    }

}"

Sleep In While Loop