Pages

Thursday, February 15, 2018

Powershell: Indeterminate Inline Progress Bar

I am currently working on removing a replicas from all of our on-premise public folders. There is quite possibly 40,000 public folders nested inside of the structure. We are looking to remove 2 copies from all replicas and the Exchange 2010 tools, while working didn't provide any progress.

So, I grabbed all the 'good' replicas.

$firstPF = get-publicfolder ".\Top" 

$GoodReplicas = $firstPF.Replicas | ?{$_ -notlike "remove this db name"} 

Get-PublicFolder -recurse | ?{$_.replicas -ne $GoodReplicas} | Set-PublicFolder -replicas $GoodReplicas

This was taking for ever and I couldn't tell if it was even running. I modified one of my previous progress bars, so that it would simply count to 100, then reset back to 1. Next I modified the code, to return the object I am currently parsing. This allows me to put the progress bar in-line with my code above and it keeps running.

Get-PublicFolder -recurse | ?{$_.replicas -ne $GoodReplicas} | %{wp3 -passthru $_} | Set-PublicFolder -replicas $GoodReplicas



You can see I use a few global variables. This helps maintain the counter between iterations. This also means that it will start at where you left off with the last run.


function wp3 {
 [CmdletBinding()] param(  
  [Parameter()][String]$JobName="Counter",
  [Parameter()]$Passthru
 )

 $envVar = get-Variable -Name $JobName -Scope Global -ErrorAction SilentlyContinue -ValueOnly
 $Times = $JobName+"_count"
 $envVar2 = get-Variable -Name $Times -Scope Global -ErrorAction SilentlyContinue -ValueOnly
 if ($EnvVar -eq $null) { 
  #Global Variable doesn't exist, create one called based on $JobName
  $Env_WPIndex = 0
  New-Variable -Name $JobName -Scope Global -Value 0 #-Visibility Private
 } else {
  #Use current global variable value.
  $env_WPIndex = [double]$EnvVar
 } 
 if ($envVar2 -eq $null) { 
  #Global Variable doesn't exist, create one called based on $JobName
  $envTimeThru = 0
  New-Variable -Name $Times -Scope Global -Value 0 #-Visibility Private
 } else {
  #Use current global variable value.
  $envTimeThru = [double]$envVar2
 }
 Write-Progress -Activity ($JobName+"("+$envTimeThru+")") -Status $([string]$Env_WPIndex+"%") -PercentComplete $Env_WPIndex 
 $env_WPIndex = $env_wpIndex + 1
 
 if ($env_wpIndex -lt 100) { 
  #if less then max object count, increment the global variable by one
  Set-Variable -Name $JobName -Scope Global -ErrorAction SilentlyContinue -Value $env_WPIndex
 } else {
  $envTimeThru = $envTimeThru + 1
  #if already greater than max, remove the global variable from machine. 
  Set-Variable -Name $JobName -Scope Global -Value 0 # -ErrorAction SilentlyContinue
 }

 Set-Variable -Name $Times -Scope Global -ErrorAction SilentlyContinue -Value $envTimeThru
 return $Passthru
}

No comments:

Post a Comment