Getting fancy with Write-Progress

Recently I watched a great CBT Nugget by Don Jones (seriously the best trainer/writer out there for PoSH) called Powershell Toolmaking and Scripting.  A lot of it was review, but I did pick up a few nuggets along the way that made watching the series well worth it.  By far my favorite was Adding Output, where he went into detail on how to use Write-Progress to add a nice progress bar into script you run that take any length of time.  Being that most of my inventory scripts run for anywhere from 5 to 45 minutes, I found this feature pretty slick.

To set it up, you’ll need three integers.  First, get the total count of objects you’ll be working on, then divide 100 by that total to get the percentage value each object is worth.  Last, assign a current int to 0.  Once you’ve done this, you can use Write-Progress with its -PercentComplete parameter by passing the current int into it, then adding the value of each object to the current at the end of each pass.

As an snippet example from my Rackspace Inventory, I do the following before my loop:

#get number of mailboxes
$totalMailboxes = $dataset.mailboxList.total
#devide total by 100 to assign the value each mailbox adds to $currentComplete
$eachMailbox = (100 / ($totalMailboxes))
#to be passed as -PercentComplete in Write-Progress
$currentComplete = 0

Then once inside the loop I call Write-Progress and add $each to $current.

Write-Progress -Activity "Fetching mailbox details" -Status "Processing permissions for $userId" -PercentComplete $currentComplete
$currentComplete += $eachMailbox

“I don’t always look at my scripts, but when I do, I do it with Write-Progress.”  -The Most Interesting PoSH Scripter In The World

Advertisements
This entry was posted in Musing, Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s