【问题标题】:PowerShell. How to process Current Item count against Total Item Count电源外壳。如何根据总项目数处理当前项目数
【发布时间】:2021-12-08 16:30:10
【问题描述】:

我有一个用于安装远程更新的脚本,一切正常。我只是想尝试添加一些类似的东西来跟踪更新的进度。

我可以通过做得到总数

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

这显示了我的总数。然后在我的ForEach 声明中,我想让它说它正在处理更新xi

下面是 ForEach 语句的片段。

ForEach($Update in $TargetUpdates){

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

[x] of [i] 部分是我迷路的地方。这可能是一件非常简单的事情,我只是无法理解它。

【问题讨论】:

    标签: powershell count


    【解决方案1】:

    使用您已有的另一种选择:

    $TargetUpdates = Get-ChildItem .
    $total = $TargetUpdates.Count
    $index = 0
    
    ForEach($Update in $TargetUpdates)
    {
        Write-Host "[${env:ComputerName} Processing Update [$((++$index))] of [$total]..."
    }
    

    【讨论】:

      【解决方案2】:

      对于进度更新,请考虑使用带有Write-Progress 的进度流。

      为了跟踪您在foreach 循环中的进度,您可以维护一个简单的计数器变量:

      $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++
      }
      

      或者,使用for 循环:

      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
      }
      

      单步 for 循环也可以用范围运算符和 ForEach-Object 模拟(尽管如果您习惯于 C 风格的语言,这可能不容易阅读):

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-09
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        相关资源
        最近更新 更多