forked from stcu/SharedScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ForEach-Progress.ps1
53 lines (46 loc) · 1.82 KB
/
ForEach-Progress.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<#
.SYNOPSIS
Performs an operation against each item in a collection of input objects, with a progress bar.
.INPUTS
System.Management.Automation.PSObject to process.
.FUNCTIONALITY
PowerShell
.EXAMPLE
1..10 |ForEach-Progress.ps1 -Activity 'Processing' {"$_"} {Write-Host "item: $_"; sleep 2}
Provides a progress indicator for a script block.
.EXAMPLE
1..10 |ForEach-Progress.ps1 |foreach {Write-Host "item: $_"; sleep 2}
Same as previous example, but adds a progress indicator within an existing pipeline.
#>
#Requires -Version 3
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand','',
Justification='This script uses $input within an End block.')]
[CmdletBinding()] Param(
# The progress title text to display.
[Parameter(Position=0)][string] $Activity = 'Processing',
# A script block to generate status text from each $PSItem ($_).
[Parameter(Position=1)][scriptblock] $Status = {$_ |ConvertTo-Json -Compress},
# A script block to execute for each $PSItem ($_).
[Parameter(Position=2)][scriptblock] $Process = {$_},
# An item to process.
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][psobject] $InputObject
)
End
{
[psobject[]] $values = $input
if(!$values) {$values = @($InputObject)}
$i,$max,$id = 0,($values.Length/100),(Get-Random)
try
{
foreach($value in $values)
{
[Collections.Generic.List[psvariable]] $ctx = New-Object PSVariable _,$value
$itemstatus = $Status.InvokeWithContext($null,$ctx,$value) |Select-Object -First 1
if(!$itemstatus) {$itemstatus = '?'}
Write-Progress $Activity $itemstatus -Id $id -PercentComplete ($i++/$max)
[Collections.Generic.List[psvariable]] $ctx = New-Object PSVariable _,$value
$Process.InvokeWithContext($null,$ctx,$value)
}
}
finally {Write-Progress $Activity -Id $id -Completed}
}