powershell - 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 部分中没有更新。
有没有办法来解决这个问题?
解决方案
您不能将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
推荐阅读
- python - 如何找到运行 git 挂钩的存储库
- r - R quantstrat:注意:“<<-”分配给“.strategy”没有可见的绑定
- c# - 如何处理 1 位和 4 位图像?
- angular - 如何让 switchMap 在 combineLatest 中触发?
- azure - 带有 VPN 的 Azure 虚拟机
- html - Django Template full width CSS
- javascript - vue2 highlight updated rows
- c++ - boost::any 结构体和无符号整数
- azure - 通过 Ansible 创建 VM 并将应用程序部署到 Azure VM
- angularjs - 如何避免在页面加载时显示 AngularJS 指令代码