r/PowerShell • • Aug 18 '17

Script Sharing How To Create Progress Bars in PowerShell

https://mcpmag.com/articles/2017/08/17/create-progress-bars-in-powershell.aspx
126 Upvotes

12 comments sorted by

8

u/Thirdbeat Aug 18 '17

Great article! I wish I had this when I started powershell Just a comment: you should add that one can set write-progress -complete after processing is done and that the activity sets the "unique Id" so you can have several write progresses. Also mabye show how it's done when processing an array (using for instead of foreach) Just my 2 cents

2

u/gigglestick Aug 19 '17

One should use the -Id parameter for multiple progress bars. Activity is not a unique Id. For evidence, try the two following examples:

# This one will show a single progress bar, switching between A and B values:
for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

# This one will show two separate progress bars, one showing A values and one showing B values:
for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Id 0 -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Id 1 -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

2

u/Thirdbeat Aug 19 '17

You know what, you are absolutely right. I was certain i had written some code that did multiple progress-bars this way, but upon testing i found out i was wrong. I'm sorry.

But i do have to add that while it is supported that only one have -ID, you cannot choose 0 ;)

2

u/gigglestick Aug 19 '17 edited Aug 20 '17

In fact, zero is the default ID, and can be specified. My code above works, as does the following without -Id on the first one because the default of the first one is zero.

Edit: Microsoft's documentation says there's no default ID, but if you change "-Id 1" to "-Id 0" in the following code, they both end up overwriting the same progress bar, which implies to me that the one without an ID is using 0 by default.

for ($a = 10; $a -le 100; $a += 10) { 
    for ($b = 10; $b -le 100; $b += 10) { 
        Write-Progress -Activity "A = $a"
        Start-Sleep -Milliseconds 100
        Write-Progress -Id 1 -Activity "B = $b"
        Start-Sleep -Milliseconds 100
    }
}

it is supported that only one have -ID

This works with 12 progress bars, addressing them by unique ID:

for ($loop = 10; $loop -le 100; $loop += 10) { 
    for ($id = 0; $id -le 12; $id++) { 
        Write-Progress -Id $id -Activity "$id - $loop"
        Start-Sleep -Milliseconds 10
    }
    Start-Sleep -Seconds 1
}

6

u/[deleted] Aug 19 '17

I made an extremely useful cmdlet called Measure-Progress that makes progress bars in PowerShell dead simple. (I originally named it ForEach-Progress, but that doesn't really make any sense.) But it does function very similarly to ForEach-Object.

Get-ChildItem *.csv | Measure-Progress { DoSomethingSlow $_ }

Or instead of a ScriptBlock, just sit in the middle of a pipeline…

Get-ChildItem *.csv | Measure-Progress | DoSomethingSlow

This will show a progress bar that increments each time an input object from the pipeline is read.

2

u/mimic751 Aug 18 '17

Thank you!

2

u/JBear_Alpha Aug 19 '17

Been implementing this for quite some time and I absolutely love it. Immediate feedback and not just a flashing cursor. Example of a SystemInfo function below:

function SYS {
<# 
.SYNOPSIS 
    Retrieve basic system information for specified workstation(s) 

.EXAMPLE 
    SYS Computer1 
#> 
param(

    [Parameter(Mandatory=$true, HelpMessage="Enter desired computername(s)")]
    [string[]] $ComputerName
)

$i=0
$j=0

function Systeminformation {

    foreach ($Computer in $ComputerName) {

        if(!([String]::IsNullOrWhiteSpace($Computer))) {

            If (Test-Connection -Quiet -Count 1 -Computer $Computer) {

                Write-Progress -Activity "Getting Sytem Information..." -Status ("Percent Complete:" + "{0:N0}" -f ((($i++) / $ComputerName.count) * 100) + "%") -CurrentOperation "Processing $($Computer)..." -PercentComplete ((($j++) / $ComputerName.count) * 100)

                Start-Job -ScriptBlock { param($Computer) 

                    #Gather specified workstation information; CimInstance only works on 64-bit
                    $computerSystem = Get-CimInstance CIM_ComputerSystem -Computer $Computer
                    $computerBIOS = Get-CimInstance CIM_BIOSElement -Computer $Computer
                    $computerOS = Get-CimInstance CIM_OperatingSystem -Computer $Computer
                    $computerCPU = Get-CimInstance CIM_Processor -Computer $Computer
                    $computerHDD = Get-CimInstance Win32_LogicalDisk -Computer $Computer -Filter "DeviceID = 'C:'"

                        [pscustomobject]@{

                            "Computer Name"=$computerSystem.Name
                            "Last Reboot"=$computerOS.LastBootUpTime
                            "Operating System"=$computerOS.OSArchitecture + " " + $computerOS.caption
                             Model=$computerSystem.Model
                             RAM= "{0:N2}" -f [int]($computerSystem.TotalPhysicalMemory/1GB) + "GB"
                            "Disk Capacity"="{0:N2}" -f ($computerHDD.Size/1GB) + "GB"
                            "Total Disk Space"="{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + " Free (" + "{0:N2}" -f ($computerHDD.FreeSpace/1GB) + "GB)"
                            "Current User"=$computerSystem.UserName
                        }
                } -ArgumentList $Computer
            }

            else {

                Start-Job -ScriptBlock { param($Computer)  
                 
                    [pscustomobject]@{

                        "Computer Name"=$Computer
                        "Last Reboot"="Unable to PING."
                        "Operating System"="$Null"
                        Model="$Null"
                        RAM="$Null"
                        "Disk Capacity"="$Null"
                        "Total Disk Space"="$Null"
                        "Current User"="$Null"
                    }
                } -ArgumentList $Computer                       
            }
        }

        else {
             
            Start-Job -ScriptBlock { param($Computer)  
                 
                [pscustomobject]@{

                    "Computer Name"="Value is null."
                    "Last Reboot"="$Null"
                    "Operating System"="$Null"
                    Model="$Null"
                    RAM="$Null"
                    "Disk Capacity"="$Null"
                    "Total Disk Space"="$Null"
                    "Current User"="$Null"
                }
            } -ArgumentList $Computer
        }
    } 
}

#Call main function
SystemInformation | Receive-Job -Wait | Select "Computer Name", "Current User", "Operating System", Model, RAM, "Disk Capacity", "Total Disk Space", "Last Reboot" | Out-GridView -Title "System Information"

}#End SYS

2

u/Old-Lost Aug 19 '17

Take a look at this ProgressManager Class I wrote a while back. I think it turned out pretty well.

1

u/fourierswager Aug 19 '17 edited Aug 19 '17

So, this is a dumb/fundamental question, but how do you actually use the class? If I'm reading it correctly, after loading it, I should be able to tab complete something like either:

[TimeSpan.ProgressManager]::new(<params from one of the constructors>)

But it appears to not be loaded in my current session...and the closest I can get to a matching tab complete is just [timespan]...I also tried tab completing [ProgressManager] and also tried searching in my current AppDomain via [System.AppDomain]::CurrentDomain.GetAssemblies()...

2

u/Old-Lost Aug 19 '17 edited Aug 19 '17

It's not [TimeSpan.ProgressManager], it's just [ProgressManager]. The code does add a ScriptProperty to the TimeSpan class that returns a string of the approximate time, but the ProgressManager class is not a child class of TimeSpan.

Here's a function that makes use of the class so you can see it in action:

function Watch-Progress {
	<#
	.SYNOPSIS
	Displays a progress bar within a Windows PowerShell command window.
	.DESCRIPTION
	The Watch-Progress CmdLet displays a progress bar in a Windows PowerShell command
    window that depicts the status of pipeline input processing.
	This CmdLet is meant to preceed a lengthy process in which you wish to monitor the flow
    of objects as they travel down the pipeline.
	The Status line is predefined to display the following fields:
		* StartTime - time the operation began.
		* Completed - how many items have been sent down the pipeline.
		* Pending - how many items remain to be sent down the pipeline.
		* RunTime - how long its been since StartTime.
		* <Count> / <Unit> - how fast the objects are being processed. This will be expressed as
                       so many items per second, minute, or hour.
		* Remaining - an estimate of how much time it will be until all items are processed.
		* <Item> - text representing the lastest object sent down the pipeline. You have full control
          of this text through the Property or Format parameters. This fields will automatically be
          truncated to 60 characters.
	Note that after all items are processed the progress bar is automatically removed.
	.PARAMETER Activity
	Specifies the first line of text in the heading above the status bar. This text describes the activity
    whose progress is being reported.
	.PARAMETER Property
	Specifies the name of a property of InputObject that represents how to display the current
    InputObject. It should be a string property or one that is easily resolvable to a string. This text
    is added to the line describing the status of the operation.
	.PARAMETER Format
	Specifies a scriptblock that returns a relatively short string to represent the current InputObject.
    This text is added to the line describing the status of the operation. Use the automatic variable
    $_ (or $PSItem) to represent the current item.
	.PARAMETER Id
	Specifies an ID that distinguishes each progress bar from the others. If omitted a random Id will
    be used.
	.PARAMETER ParentId
	Identifies the parent activity of the current activity. Omit this parameter if the current activity has
    no parent activity.
	.PARAMETER InputObject
	Specifies the objects to be monitored. If part of a pipeline, Watch-Progress will collect all input
    before sending any object further down the pipeline.
	.EXAMPLE
	Get-ChildItem -File | Watch-Progress -Activity 'Searching files' -Property Name | % {
        Select-String -Pattern 'Jones' -SimpleMatch -LiteralPath $_.FullName
    }

	Searches all files in the current folder for 'Jones'. Display a progress bar in the PS window as
    the ForEach-Object command processes each file.
	.INPUTS
	Any
	.OUTPUTS
	Same as input; they are not modified in any way.
	.NOTES
	The Remaining estimate is not simply a function of start time, current time, and items processed,
    but is calculated based on the speed of the last 10% of items (or 10 if fewer than 10) processed.
    This is an attempt to get a better estimate of time left than a strictly linear calculation would provide.
	Uses ProgressManager class from https://pastebin.com/QrVLYZST

	#>
	[CmdletBinding(DefaultParameterSetName = 'Format')]
	Param (
		[Parameter(Position = 0)][string]$Activity = 'Watching Progress',
		[Parameter(Position = 1)][int32]$Id = (Get-Random -Maximum 1000),
		[Parameter()][int32]$ParentId = -1,
		[Parameter(ParameterSetName = 'Format')][scriptblock]$Format = { $_.ToString() },
		[Parameter(ParameterSetName = 'Property')][ValidateNotNullOrEmpty()][string]$Property,
		[Parameter(Mandatory, ValueFromPipeline)][Object[]]$InputObject
	)
	$List = @($Input)
	if ($List.Count -eq 0 -and $PSBoundParameters.ContainsKey('InputObject')) {
		$List = @($InputObject)
	}
	if ($PsCmdlet.ParameterSetName -eq 'Property') {
		$Format = [scriptblock]::Create("`$_.$Property")
	}
	[ProgressManager]$pm = [ProgressManager]::new($List.Count, $Id, $ParentId, $Activity, $Format)
	try {
		foreach ($item in $List) {
			$pm.WriteProgress($item)
			Write-Output $item
			$pm.Update()
		}
	} finally {
		$pm.Complete()
	}
}

HTH

1

u/fourierswager Aug 20 '17

Awesome, thank you!

2

u/jagrock84 Aug 19 '17

Nice article. I only caution that, as with writing to console, it slows down scripts if there are lots of processes. I tend to create a stop watch before the main loop I want to have a progress and only update the progress bar every 1 sec. For script I have running against 50k objects, this can shave off several minutes.

As you can see in the example below, it's 60 seconds updating progress every time. The whole process takes less than a sec in the 2nd one (I put in an extra if condition to force the progress to show at least once).

cls

$sw = New-Object System.Diagnostics.Stopwatch
$sw2 = New-Object System.Diagnostics.Stopwatch

$sw.Start()

$totalTimes = 100000

$i = 0

for ($i=0;$i -lt $totalTimes; $i++) {

    $percentComplete = ($i / $totalTimes) * 100

    Write-Progress -id 1 -Activity 'Doing thing' -Status "Did thing $i  times" -PercentComplete $percentComplete

}

$sw.Elapsed.TotalSeconds

Write-Progress -id 1 -Activity 'Doing thing' -Completed
Start-Sleep -Seconds 1

$sw.Restart()
$sw2.Start()

$i = 0

for ($i=0;$i -lt $totalTimes; $i++) {

    $percentComplete = ($i / $totalTimes) * 100

    If (($sw2.Elapsed.TotalMilliseconds -ge 1000) -or ($i -le 1)) {

        Write-Progress -ID 2 -Activity 'Doing thing2' -Status "Did thing $i  times" -PercentComplete $percentComplete
        $sw2.Restart()

    }

}

$sw.Elapsed.TotalSeconds
Write-Progress ID 2 -Activity 'Doing thing2' -Completed