Updating hash table values in a 'foreach' loop in PowerShell

后端 未结 10 1605
清歌不尽
清歌不尽 2020-12-29 02:03

I\'m trying to loop through a hash table and set the value of each key to 5 and PowerShell gives an error:

$myHash = @{}
$myHash[\"a\"] = 1
$myHash[\"b\"] =          


        
10条回答
  •  隐瞒了意图╮
    2020-12-29 02:43

    It seems when you update the hash table inside the foreach loop, the enumerator invalidates itself. I got around this by populating a new hash table:

    $myHash = @{}
    $myHash["a"] = 1
    $myHash["b"] = 2
    $myHash["c"] = 3
    
    $newHash = @{}
    foreach($key in $myHash.keys){
        $newHash[$key] = 5
    }
    $myHash = $newHash
    

提交回复
热议问题