Skip to content

Instantly share code, notes, and snippets.

@X1aomu
Last active February 8, 2025 08:59
Show Gist options
  • Save X1aomu/e3320cf7ef20a3b0c1751a874a43ffbf to your computer and use it in GitHub Desktop.
Save X1aomu/e3320cf7ef20a3b0c1751a874a43ffbf to your computer and use it in GitHub Desktop.
A powershell sleep function with progress bar, which is precise(no cumulative error), not affected by system clock, and highly readable.
function Start-Sleep-With-Progress {
param (
[string]$Activity,
[int]$Seconds
)
$duration = New-TimeSpan -Seconds $Seconds
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
while ($stopWatch.Elapsed -lt $duration) {
$elapsed = $stopWatch.Elapsed
$remaining = [TimeSpan]::FromTicks([math]::Max(($duration - $elapsed).Ticks, 0))
$percent = ($elapsed.TotalMilliseconds / $duration.TotalMilliseconds) * 100
$progressText = "$((New-TimeSpan -Seconds $elapsed.TotalSeconds).ToString("c")) / $((New-TimeSpan -Seconds $duration.TotalSeconds).ToString("c"))"
Write-Progress `
-Activity "$Activity" `
-CurrentOperation "Sleeping" `
-Status $progressText `
-PercentComplete $percent `
-SecondsRemaining $remaining.TotalSeconds
Start-Sleep -Milliseconds $([math]::Min(50.0, $remaining.TotalMilliseconds))
}
$stopWatch.Stop()
Write-Progress -Activity "$Activity" -Completed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment