Monthly Archive

Categories

PowerShell sleep

Getting PowerShell to sleep or pause during execution can sometimes be useful. This is how you can do a PowerShell sleep.

The starting point is Start-Sleep

PS> Get-Command Start-Sleep -Syntax

Start-Sleep [-Seconds] <int> [<CommonParameters>]

Start-Sleep -Milliseconds <int> [<CommonParameters>]

 

You can set a time in seconds or milliseconds that you want PowerShell to pause

PS> 1..5 | foreach {
Get-Date
Start-Sleep -Seconds 30
}

30 June 2018 20:08:02
30 June 2018 20:08:32
30 June 2018 20:09:02
30 June 2018 20:09:32
30 June 2018 20:10:02

 

If you need your script to sleep for more than a minute you still need to use seconds. So to sleep for 3 minutes use:

Start-Sleep -Seconds 180

 

If you want the pause to be under manual control use the pause function:

PS> 1..5 | foreach {
Get-Date
pause
}

30 June 2018 20:17:57
Press Enter to continue...:
30 June 2018 20:18:01
Press Enter to continue...:
30 June 2018 20:18:16
Press Enter to continue...:
30 June 2018 20:18:33
Press Enter to continue...:
30 June 2018 20:18:43
Press Enter to continue...:

 

The drawback is that it’s a manual process so not good for soemthing running in the middle of the night and you get the display contaminated with “press enter to continue…” statements.

Pause is a function that PowerShell automatically creates. It has a simple definition:

$null = Read-Host 'Press Enter to continue...'

Comments are closed.