Running PowerShell Tasks with Progress Bar

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
{
  param
  (
    [Parameter(Mandatory)]
    [ScriptBlock]
    $Task
  )
  
  try
  {
    $ps = [PowerShell]::Create()
    $null = $ps.AddScript($Task)
    $handle = $ps.BeginInvoke()
  
    $i = 0
    while(!$handle.IsCompleted)
    {
      Write-Progress -Activity 'Hang in...' -Status $i -PercentComplete ($i % 100)
      $i++
      Start-Sleep -Milliseconds 300
    }
    Write-Progress -Activity 'Hang in...' -Status $i -Completed
    $ps.EndInvoke($handle)
  }
  finally
  {
    $ps.Stop()
    $ps.Runspace.Close()
    $ps.Dispose()
  } 
}

Just try it:

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

Twitter This Tip! ReTweet this Tip!