首页 > 解决方案 > foreach 循环:如何在循环内更新集合变量?

问题描述

有没有办法改变循环的集合变量不能从其循环内更新并在下一次迭代中使用新值的行为?

例如:

$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 部分中没有更新。

有没有办法来解决这个问题?

标签: powershellloopsforeach

解决方案


您不能将foreach循环与循环主体中正在修改的集合一起使用。

尝试这样做实际上会导致错误( Collection was modified; enumeration operation may not execute.)

没有看到错误的原因是您实际上并没有修改原始集合本身;您正在将一个的集合实例分配给同一个变量,但这与枚举的原始集合实例无关。

您应该改用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

推荐阅读