Created
March 4, 2014 19:30
-
-
Save glombard/9353819 to your computer and use it in GitHub Desktop.
A simple module to wrap a nicer interface around Write-Progress. It allows you to first register each step you're going to perform and then you activate/set each step as you progress through your script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # A simple module to wrap a nicer interface around Write-Progress. | |
| # It allows you to first register each step you're going to perform and | |
| # then you activate/set each step as you progress through your script. | |
| $progress = New-Module -ScriptBlock { | |
| [string]$title = 'Progress' | |
| [int]$totalSteps = 0 | |
| function Activity { | |
| param([string]$activity) | |
| $script:title = $activity | |
| } | |
| function Step { | |
| param([string]$status) | |
| $position = $script:totalSteps | |
| $script:totalSteps += 1 | |
| [Func[int]]$getTotal = { return $script:totalSteps } | |
| $s = New-Module -ArgumentList $title,$status,$position,$getTotal -ScriptBlock { | |
| $activity = $args[0] | |
| $status = $args[1] | |
| $position = $args[2] | |
| $getTotal = $args[3] | |
| function Set { | |
| $total = $getTotal.Invoke() | |
| $pos = $position + 1 | |
| Write-Host "Step $pos of ${total}: $status" -ForegroundColor Green -BackgroundColor Black | |
| $p = $position / $total * 100 | |
| Write-Progress -Activity $script:activity -status $status -percentComplete $p | |
| } | |
| Export-ModuleMember -Function Set | |
| } -AsCustomObject | |
| return $s | |
| } | |
| function Done { | |
| param([string]$status = "Done") | |
| Write-Progress -Activity $script:title -status $status -percentComplete 100 | |
| } | |
| Export-ModuleMember -Function Activity, Step, Done | |
| } -AsCustomObject | |
| # Example usage: | |
| # First register the activity description and steps: | |
| $progress.Activity("Getting the file you need") | |
| $downloading = $progress.Step("Downloading") | |
| $extracting = $progress.Step("Extracting") | |
| # Now set each step along the way: | |
| $downloading.Set() | |
| [System.Threading.Thread]::Sleep(1000) | |
| $extracting.Set() | |
| [System.Threading.Thread]::Sleep(1000) | |
| $progress.Done() | |
| [System.Threading.Thread]::Sleep(1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment