gpt4 book ai didi

loops - 修改未枚举的对象时出错

转载 作者:行者123 更新时间:2023-12-02 23:14:18 25 4
gpt4 key购买 nike

我有以下脚本:

$serverList = @{ 
"Server1Name" = @{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server2Name" = @{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server3Name" = @{ "WindowsService1" = "Status" };
"Server4Name" = @{ "WindowsService1" = "Status" };
"Server5Name" = @{ "WindowsService1" = "Status" };
"Server6Name" = @{ "WindowsService1" = "Status" }
}

$copy = $serverList.Clone()

foreach ($server in $copy.Keys) {
foreach ($service in $copy[$server].Keys) {
$serviceInfo = Get-Service -ComputerName $server -Name $service
$serverList[$server][$service] = $serviceInfo.Status
}
}

我确保我没有修改正在枚举的哈希表,但是运行脚本时仍然出现此错误:
Collection was modified; enumeration operation may not execute.At line:14 char:14
+ foreach ($service in $copy[$server].Keys) {
+ ~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException

我在这里阅读: http://blog.matticus.net/2013/11/powershell-clearing-values-within.html。如果我将代码表复制到那里,它对我来说不会出错。

我的问题可能与嵌套的foreach循环有关吗?我的代码有错误吗?谁能对此有所启示?

最佳答案

Powershell不喜欢您要修改要迭代的集合。

开始时,您创建了一个名为$ copy的克隆来避免此问题。 clone()是“浅拷贝”,因此每个键所引用的对象在副本中都是相同的。

在这行上:

$serverList[$server][$service] = $serviceInfo.Status

您修改内部集合-当前正在对其进行迭代。

实际上,outter集合从不修改,仅被引用,因此outter clone()调用是不必要的。相反,您应该克隆内部集合。
像这样(未经测试):
$serverList = @{ 
"Server1Name" = @{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server2Name" = @{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server3Name" = @{ "WindowsService1" = "Status" };
"Server4Name" = @{ "WindowsService1" = "Status" };
"Server5Name" = @{ "WindowsService1" = "Status" };
"Server6Name" = @{ "WindowsService1" = "Status" }
}



foreach ($server in $serverList.Keys) {
$copy = $serverList[$server].clone();
foreach ($service in $copy.Keys) {
$serviceInfo = Get-Service -ComputerName $server -Name $service
$serverList[$server][$service] = $serviceInfo.Status
}
}

关于loops - 修改未枚举的对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21885139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com