在循环期间显示进展

use*_*700 3 powershell loops progress

我有一个ForEach循环,我希望显示进度:

1..254 | ForEach-Object {Test-Connection -ErrorAction SilentlyContinue -count 
1 -TimeToLive 32 "$ipcut.$_"}
#^need to get a progress bar somewhere here^
Run Code Online (Sandbox Code Playgroud)

我已尝试在上面的代码中的各个地方使用write-progress,并且似乎无法使其工作,因为它从1-254循环.

Jos*_*efZ 5

像这样的东西?

$ipCut ='192.168.1'    ### not included in the original question

$arrTest = 1..254
$all = $arrTest.Count
$i = 0
$arrTest | ForEach-Object {
   Write-Progress -PercentComplete (
       $i*100/$all) -Activity "PINGs completed: $i/$all"  -Status 'Working'
   Test-Connection -ErrorAction SilentlyContinue -count 1 -TimeToLive 32 "$ipcut.$_"
   $i++
}
Run Code Online (Sandbox Code Playgroud)

参考:Write-Progress cmdlet:

Write-Progresscmdlet在Windows PowerShell命令窗口中显示进度条,该窗口描述正在运行的命令或脚本的状态.您可以选择条形图反映的指示符以及进度条上方和下方显示的文本.

编辑:重写代码作为单行代码很容易:只需用分号(;)而不是换行符分隔特定命令:

$arr=1..254; $all=$arr.Count; $i=0; $arr|ForEach-Object{Write-Progress -PercentComplete ($i*100/$all) -Activity "PINGs completed: $i/$all"  -Status 'Working'; Test-Connection -ErrorAction SilentlyContinue -count 1 -TimeToLive 32 "$ipcut.$_"; $i++}
Run Code Online (Sandbox Code Playgroud)

或更简单的硬编码1..254254不是$arr$all分别:

$i=0; 1..254|ForEach-Object{Write-Progress -PercentComplete ($i*100/254) -Activity "PINGs completed: $i/254"  -Status 'Working'; Test-Connection -ErrorAction SilentlyContinue -count 1 -TimeToLive 32 "$ipcut.$_"; $i++}
Run Code Online (Sandbox Code Playgroud)