PowerShell: Sleep with progress bar

Wrote this function to provide a common way to add sleep and give progress updates.

Set the sleep time by creating a hash table (aka dictionary) specifying the hours/minutes/seconds you want to pause your script for. You don’t have to specify all of hours, minutes or seconds, just one or more. Call the SleepProgress function with your hash table as the parameter.

function SleepProgress([hashtable]$SleepHash){
     [int]$SleepSeconds = 0
     foreach($Key in $SleepHash.Keys){
             "Seconds" {
                 $SleepSeconds = $SleepSeconds + $SleepHash.Get_Item($Key)
             "Minutes" {
                 $SleepSeconds = $SleepSeconds + ($SleepHash.Get_Item($Key) * 60)
             "Hours" {
                 $SleepSeconds = $SleepSeconds + ($SleepHash.Get_Item($Key) * 60 * 60)
     for($Count=0;$Count -lt $SleepSeconds;$Count++){
         $SleepSecondsString = [convert]::ToString($SleepSeconds)
         Write-Progress -Activity "Please wait for $SleepSecondsString seconds" -Status "Sleeping" -PercentComplete ($Count/$SleepSeconds*100)
         Start-Sleep -Seconds 1
     Write-Progress -Activity "Please wait for $SleepSecondsString seconds" -Completed
$SleepTime = @{"Seconds" = 30;"Minutes" = 1}
SleepProgress $SleepTime

This script demonstrates the use of switch, write-progress and hash tables.

This entry was posted in PowerShell and tagged , , , , , , , , . Bookmark the permalink.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.