PowerShell pause

PowerShell pause – how can you pause a PowerShell script?

Two ways come to mind.

First if you just want the script to pause for a specified time period then you can use Start-Sleep

1..10 |
foreach {
   $PSItem
   if ($PSItem -eq 5) {
     Write-Warning -Message “Starting sleep”
     Start-Sleep -Seconds 5
   }
}

Run this and you’ll see the numbers 1-5 output then then warning message. After the delay you’ll see the numbers 6-10 output.

But what if you want to control the pause manually? Not sure if there are advantages to this approach but if you do need to do this you can use Read-Host

1..10 |
foreach {
   $PSItem
   if ($PSItem -eq 5) {
     Read-Host -Prompt “Press Enter key to continue”
   }
}

You’ll see the numbers 1-5 output then the message

Press Enter key to continue:

After pressing the enter key the script continues and outputs 6-10

Don’t know why you’d want to do this in an automation scenario but the technique is there if you need it – I don’t recommend the approach.

There are also a few cmdlets that can be used under specific circumstances:

Wait-Event
Wait-Job
Wait-Process
Wait-VM

Also check the –wait parameter on Restart-Computer

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

3 Responses to PowerShell pause

  1. Frank B says:

    Shorter way to do the read-host, just use “Pause”

  2. Luke says:

    The While statement can also be a way to wait, for example in association with Test-NetConnection to test if a port is available or potentially other cmdlets with the Test verb.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s