我试图遍历哈希表并将每个键的值设置为5,PowerShell给出了一个错误:

$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3

foreach($key in $myHash.keys){
    $myHash[$key] = 5
}

枚举集合时发生错误:
Collection was modified; enumeration operation may not execute..
At line:1 char:8
+ foreach <<<< ($key in $myHash.keys){
    + CategoryInfo          : InvalidOperation: (System.Collecti...tableEnumer
   ator:HashtableEnumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

有什么用,我该如何解决?

最佳答案

您无法在枚举时修改Hashtable。您可以执行以下操作:

$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3

$myHash = $myHash.keys | foreach{$r=@{}}{$r[$_] = 5}{$r}

编辑1

这对您来说是否更简单:
$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3

foreach($key in $($myHash.keys)){
    $myHash[$key] = 5
}

关于powershell - 在PowerShell中的 'foreach'循环中更新哈希表值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5879871/

10-09 21:40