Home > Blockchain >  PowerShell. How to process Current Item count against Total Item Count
PowerShell. How to process Current Item count against Total Item Count

Time:12-09

I have a script for installing remote updates and that all works fine. I'm just looking to try and add some semblance of keeping track of the progress of the updates.

I can get the total count by doing

$TargetUpdates = Get-ChildItem "C:\Updates -Recurse
$TargetUpdates.Count

and this shows my total count. And then in my ForEach statement I want it to say it's processing update x of i

below is a snippit of the ForEach statement.

ForEach($Update in $TargetUpdates){

Write-Host "[${Env:ComputerName} Processing Update [x] of [i]...
}

The [x] of [i] part is where I'm lost. It's probably something real simple I'm just not able to get my head around it.

CodePudding user response:

Another alternative using what you already have:

$TargetUpdates = Get-ChildItem .
$total = $TargetUpdates.Count
$index = 0

ForEach($Update in $TargetUpdates)
{
    Write-Host "[${env:ComputerName} Processing Update [$((  $index))] of [$total]..."
}

CodePudding user response:

For progress updates, consider using the progress stream with Write-Progress.

For keeping track of how far your are along in a foreach loop, you can maintain a simple counter variable:

$counter = 1

foreach($update in $TargetUpdates){
  Write-Progress -Activity "Processing updates" -Status "Process update [$counter] or [$($TargetUpdates.Count)]" -PercentComplete (($TargetUpdates.Count / $counter) * 100)

  # do actual work here
  Start-Sleep -Milliseconds 200

  # remember to increment the counter
  $counter  
}

Alternatively, use a for loop:

for($i = 0; $i -lt $TargetUpdates.Count; $i  ){
  Write-Progress -Activity "Processing updates" -Status "Process update [$($i   1)] of [$($TargetUpdates.Count)]" -PercentComplete (($TargetUpdates.Count / ($i 1)) * 100)

  $update = $TargetUpdates[$i]

  # do actual work here
  Start-Sleep -Milliseconds 200
}

Single-step for loops can also be emulated with the range operator and ForEach-Object (although this might not be easily readable if you're used to C-style languages):

0..$($TargetUpdates.Count - 1) |ForEach-Object {
  Write-Progress -Activity "Processing updates" -Status "Process update [$($_   1)] of [$($TargetUpdates.Count)]" -PercentComplete (($TargetUpdates.Count / ($_   1)) * 100)

  $update = $TargetUpdates[$_]

  # do actual work here
  Start-Sleep -Milliseconds 200
}
  • Related