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!

Change mount points drive letter | Powershell

If you want to change location of mount points from Powershell you can do this in this way:

Get-WmiObject -Class Win32_MountPoint |
where {($_.Directory -like ‘Win32_Directory.Name="F:\\D*") -or ($_.Directory -like ‘Win32_Directory.Name="F:\\Q*") -or ($_.Directory -like ‘Win32_Directory.Name="F:\\R*") -or ($_.Directory -like ‘Win32_Directory.Name="F:\\L*")} |
foreach {
   $vol = $_.Volume
   $objj = Get-WmiObject -Class Win32_Volume | where {$_.__RELPATH -eq $vol}
   $ggg = ($objj.Name).Replace("F:","H:");
   echo $ggg;
   New-Item -ItemType directory -Path $ggg
   $objj.AddMountPoint($ggg)
}

To list all of them:

Get-WmiObject Win32_Volume -Filter "DriveType='3'" | ForEach {
    New-Object PSObject -Property @{
        Name = $_.Name
        Label = $_.Label
        FreeSpace_GB = ([Math]::Round($_.FreeSpace /1GB,2))
        TotalSize_GB = ([Math]::Round($_.Capacity /1GB,2))
    }
}

Links:
http://learn-powershell.net/2012/08/10/locating-mount-points-using-powershell/
http://itknowledgeexchange.techtarget.com/powershell/disks-part-4-mount-points/