powershell - foreach 循环 : How to update collection variable within loop?

标签 powershell loops 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

如果您运行此代码,循环将执行多次。 但是,由于第一次迭代 $items1,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/

相关文章:

powershell - 检查远程机器上的进程所有者并在所有者为 xyz 时终止它

Python Selenium 处理带有长 URL 列表的超时异常

java - 使用循环将字符串存储在列表中,然后打印列表

php - foreach 循环中的 foreach 循环

jquery - jQuery 中的异步 foreach

powershell - 标题名称和跳过第一行

json - 如何在 powershell 中替换 json 文件中的属性

java - 如何访问网格 Pane 中的控件?

c# - C#中的并行迭代?

windows - 在 windows powershell 中使用 svn 缺少参数 -m