Often times I need to run some command on a large set of objects, say a WMI query on a few hundred PCs. Here is a simple script to have an easy way to show a progress bar using the built-in Write-Progress cmdlet. In my PS profile it is aliased as “bar” so I can do the following:
Get-Content computers.txt | bar |% {Get-WMIObject Win32_ComputerSystem -ComputerName $_} | Export-Csv ComputerInfo.csv
One thing to keep in mind is that the script should be placed early in the pipeline, as it consumes all objects before passing them on in order to count them. This is fine as long as the preceding commands are quick, like getting names from files, AD, SQL etc. It does not matter what kind of objects are passed through the script.
Here is the script (Show-Progress.ps1):
# Store all pipeline objects in an array so we can count them
$InputArray = @($Input)
# Initialize the counter and length ( divided by 100 so we get the percentage)
$counter = 1
$length = $InputArray.Length / 100
# Push the objects down the pipeline while updating our progress bar
$InputArray | foreach {
Write-Progress "Processing..." "$_" -perc ([Int]$counter++/$length)
$_
}
Enjoy,
Arnoud