How to add progress bar in your PowerShell scripts?

Today you will learn how to add progress bar in your code. In last post I described how to combine CSV files and this time I’m gonna show how to use those files and add cool feature to script.

Progress bar

Script is based on Write-Progress cmdlet which displays a progress bar in a Windows PowerShell command window that depicts the status of a running command or script. You can select the indicators that the bar reflects and the text that appears above and below the progress bar. More info – link.

While running below script you will notice additional information about script progress:

Progress bar
Progress bar

Final script:

#Progress parameter
$Progress = @{
    Activity = 'Counting users in report files:'
    CurrentOperation = "Loading"
    Status = 'Collecting data'
    PercentComplete = 0
}
 
Write-Progress @Progress
$i = 0

#Get all CSV files and filter by CSV name 
$CSVFiles = Get-ChildItem C:\Users\$env:username\Desktop\files\*.csv | Where-Object {$_.BaseName -match "User list"}

#Setup array
$Array = @()

#Looping each file
Foreach($File in $CSVFiles)
{
    $i++
    [int]$percentage = ($i / $CSVFiles.Count)*100
    $Name = $null
    $Name = $file.name
    $progress.CurrentOperation = "$name"
    $progress.Status = 'Processing file: '
    $progress.PercentComplete = $percentage
 
    Write-Progress @Progress 
    
    Start-Sleep -Milliseconds 600

        $CSV = $null
        $Object = $null

        #Import CSV file and count users
        Try
        {
            $CSV = import-csv $file.FullName -ErrorAction Stop
            $Object = [pscustomobject][ordered] @{
                
                "Report Date" = $file.CreationTime
                "Users count" = ($CSV.samaccountname).count
            
            }
            $Array += $Object
        }
        Catch
        {
            Write-Warning $_.Exception.Message
            Continue
        }
}
#Save results to CSV
$Array = $Array | Sort-Object "Report date" -Descending
$Array | Export-Csv -Path C:\users\$env:username\desktop\results.csv -NoTypeInformation

Output in console ($Array):

Results
Results

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.