Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Created March 23, 2016 14:44
Show Gist options
  • Save ctigeek/bd637eeaeeb71c5b17f4 to your computer and use it in GitHub Desktop.
Save ctigeek/bd637eeaeeb71c5b17f4 to your computer and use it in GitHub Desktop.
Powershell sleep function, with progress bar.
function Start-Sleep($seconds) {
$doneDT = (Get-Date).AddSeconds($seconds)
while($doneDT -gt (Get-Date)) {
$secondsLeft = $doneDT.Subtract((Get-Date)).TotalSeconds
$percent = ($seconds - $secondsLeft) / $seconds * 100
Write-Progress -Activity "Sleeping" -Status "Sleeping..." -SecondsRemaining $secondsLeft -PercentComplete $percent
[System.Threading.Thread]::Sleep(500)
}
Write-Progress -Activity "Sleeping" -Status "Sleeping..." -SecondsRemaining 0 -Completed
}
@jcefoli
Copy link

jcefoli commented Jan 6, 2022

Is there a way to fix the progress bar showing at 100% for a few seconds when the loop starts before correcting itself?

@ctigeek
Copy link
Author

ctigeek commented Jan 7, 2022

@jcefoli I just tested it and I'm not seeing that behavior. Are you using it in newer powershell core? I've only tested it in legacy powershell.

@jcefoli
Copy link

jcefoli commented Jan 7, 2022

I tested this a bit and I see what is happening. It's not very apparent if the countdown is short, but I had a 1 hour countdown, and for a while, it was completely filled in, then after some time, jumped back down and started slowly incrementing.

In the Write-Progress commandlet, the -PercentComplete parameter will display the progress bar fully highlighted if its value is 0 or a decimal less than 1. Once it hits 1, it will calculate the filled in area properly.

I tricked it by doing this:

if ($percent -lt 1) {$progressBarPercent = 1 } else { $progressBarPercent = $percent }
 Write-Progress -Activity "Sleeping" -Status "Sleeping..." -SecondsRemaining $secondsLeft -PercentComplete $progressBarPercent 

@petvo78
Copy link

petvo78 commented Jan 31, 2022

Great stuff. Thanks.

@recycleleash
Copy link

awesome!! thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment