Monthly Archive

Categories

PowerShell sleep

PowerShell use tends to be very interactive. You run a command at the console and get some results. You run a script and get some results. How do you make PowerShell sleep?

There’s a few ways you can make PowerShell code sleep.

 

First there’s Start-Sleep

PS> for ($i=0; $i -le 10; $i++){
>> if ($i -eq 5) {
>> Get-Date
>> Start-Sleep -Seconds 30
>> Get-Date
>> }
>> }

30 January 2018 14:06:21
30 January 2018 14:06:51

I use Start-Sleep when starting a bunch of virtual machines to ensure one is fully up and running before attempting to start the next.

 

You can use the pause function to add a manually controlled delay

PS> for ($i=0; $i -le 10; $i++){
>> if ($i -eq 5) {
>> Get-Date
>> pause
>> Get-Date
>> }
>> }

30 January 2018 14:08:57
Press Enter to continue...:
30 January 2018 14:09:44

 

Pause is a function created when you start PowerShell

PS> Get-Command pause | select definition

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

so if you prefer you can use Read-Host

 

You could also use a workflow and suspend the job

PS> workflow w1 {
>> for ($i=0; $i -le 10; $i++){
>> if ($i -eq 5) {
>> Get-Date
>> Suspend-Workflow
>> Get-Date
>> }
>> }
>> }
PS> w1 -AsJob

Id Name PSJobTypeName   State HasMoreData  Location  Command
-- ---- -------------   ----- -----------  --------  -------
3  Job3 PSWorkflowJob Running        True  localhost      w1

PS> Get-Job

Id Name PSJobTypeName     State HasMoreData  Location Command
-- ---- -------------     ----- -----------  -------- -------
3  Job3 PSWorkflowJob Suspended        True localhost      w1


PS> Resume-Job -Id 3

Id Name PSJobTypeName   State HasMoreData  Location Command
-- ---- -------------   ----- -----------  -------- -------
3  Job3 PSWorkflowJob Running        True localhost      w1


PS> Get-Job

Id Name PSJobTypeName     State HasMoreData  Location Command
-- ---- -------------     ----- -----------  -------- -------
3  Job3 PSWorkflowJob Completed        True localhost      w1


PS> Receive-Job -Id 3

30 January 2018 18:39:25
30 January 2018 18:40:39

 

Remember that workflows aren’t available on PowerShell v6

Comments are closed.