Running PowerShell Tasks with Progress Bar

by Aug 4, 2016

PowerShell 2+

Sometimes it may take some time for a PowerShell command to complete, and while the command is working, the user gets no visual clue.

Here is a simple function that uses a background thread to execute long-running commands. In the foreground, it displays a progress bar. If the user decides to abort by pressing CTRL+C, the function terminates the background thread.

function Invoke-WithProgressBar
    $ps = [PowerShell]::Create()
    $null = $ps.AddScript($Task)
    $handle = $ps.BeginInvoke()
    $i = 0
      Write-Progress -Activity 'Hang in...' -Status $i -PercentComplete ($i % 100)
      Start-Sleep -Milliseconds 300
    Write-Progress -Activity 'Hang in...' -Status $i -Completed

Just try it:

PS> Invoke-WithProgressBar -Task { Get-Hotfix }

Twitter This Tip! ReTweet this Tip!