有没有办法改变循环的集合变量无法从其循环内更新并在下一次迭代中使用新值的行为?
例如:
$items = @(1,1,1,2)
$counter = 0
foreach ($item in $items) {
$counter += 1
Write-Host "Iteration:" $counter " | collection variable:" $items
$item
$items = $items | Where-Object {$_ -ne $item}
}
$counter
如果您运行此代码,循环将执行多次。
但是,由于第一次迭代 $items
从 1,1,1,2
更改为仅包含 2
,循环应该只运行再一次。
我怀疑这是因为集合变量 $items
在 foreach 部分没有更新。
有办法解决这个问题吗?
最佳答案
您不能将 foreach
循环与正在循环主体中修改的集合一起使用。
尝试这样做实际上会导致错误(集合已修改;枚举操作可能无法执行。
)
您没有看到错误的原因是您实际上并没有修改原始集合本身;您正在将一个新 集合实例分配给同一个变量,但这与被枚举的原始集合实例无关。
您应该改用while
循环,在其条件下,$items
变量引用在每次迭代中重新计算:
$items = 1, 1, 1, 2
$counter = 0
while ($items) { # Loop as long as the collection has at last 1 item.
$counter += 1
Write-Host "Iteration: $counter | collection variable: $items"
$item = $items[0] # access the 1st element
$item # output it
$items = $items | Where-Object {$_ -ne $item} # filter out all elements with the same val.
}
现在你只有 2 次迭代:
Iteration: 1 | collection variable: 1 1 1 2
1
Iteration: 2 | collection variable: 2
2
关于powershell - foreach 循环 : How to update collection variable within loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382571/