Every once in a while, I need to have a nice way to monitor progress of a script. I used to add write-host messages and echo variables back so I could see counters – but, there’s progress bars for that. This is how you use them.


#Progress bars for scripts
# A Quick Array to have data
$fruit = @('Apples','Oranges','Bananas')

#
# Main Activity is -Activity.  Subtasks are -id 1 and subtasks of id 1 are -id 2
#
# region remarks make it easier to collapse sections of code during edit
#

#region Phase1
Write-Progress -Activity "Doing Cool Things" -Status 'Progress Phase 1/3 Prerequisites:' -PercentComplete "33"

Write-Progress -id 1 -Activity "Testing connectivity" -Status 'Progress:' -PercentComplete "25"
Start-Sleep -s 1
Write-Progress -id 1 -Activity "locating" -Status 'Progress:' -PercentComplete "50"
Start-Sleep -s 1
Write-Progress -id 1 -Activity "test file directory" -Status 'Progress:' -PercentComplete "90"
Start-Sleep -s 1
Write-Progress -id 1 -Activity "test file directory" -Status 'Progress:' -Completed
Start-Sleep -s 1
#endregion Phase1

#region Phase2
Write-Progress -Activity "Generating Report" -Status 'Progress Phase 2/3 Processing:' -PercentComplete "67"

Write-Progress -id 1 -Activity "Finding folders" -Status 'Progress:' -PercentComplete "10"
Start-Sleep -s 1
Write-Progress -id 1 -Activity "Harvesting Fruit" -Status 'Progress:' -PercentComplete "50" -CurrentOperation "discoverd $($fruit.count) items"
Start-Sleep -s 1




$progress = 1

$recordcount = $fruit.count
    if (!($recordcount))
    {
        $recordcount = 1
    }

   foreach ($fruitype in $fruit)
    {
        Write-Progress -id 2 -Activity "Listing Each Fruit" -Status 'Progress:' -PercentComplete ( 100/$recordcount * $progress)
  $progress++
  $fruitype
  Start-Sleep -s 1

    }


Write-Progress -id 1 -Activity "Harvesting Fruit" -Status 'Progress:' -Completed
Start-Sleep -s 1
#endregion Phase2

#region Phase3

Write-Progress -Activity "Doing Cool Things" -Status 'Progress Phase 3/3 Prerequisites:' -Completed
Start-Sleep -s 3

#endregion Phase3

I also started adding region tags to my code to help collapse sections of the code that I didn’t need to look at. This is how you use them.


#region Phase1
random code here.
#endregion Phase1