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"] = 2 $myHash["c"] = 3 foreach($key in $myHash.keys){ $myHash[$key] = 5 }
An error occurred while enumerating through a collection:
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
What gives and how do I resolve this problem?
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
And, you can add keys and values to a hash table by using the addition operator ( + ) to add a hash table to an existing hash table. For example, the following statement adds a "Time" key with a value of "Now" to the hash table in the $hash variable. You can also add values that are stored in variables.
Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.
GetEnumerator in PowerShell is used to iterate through the Hashtable or array to read data in the collection. GetEnumerator doesn't modify the collection data. Use foreach or foreach-object in PowerShell to iterate over the data read from the GetEnumerator.
You can't modify Hashtable while enumerating it. This is what you can do:
$myHash = @{} $myHash["a"] = 1 $myHash["b"] = 2 $myHash["c"] = 3 $myHash = $myHash.keys | foreach{$r=@{}}{$r[$_] = 5}{$r}
Edit 1
Is this any simpler for you:
$myHash = @{} $myHash["a"] = 1 $myHash["b"] = 2 $myHash["c"] = 3 foreach($key in $($myHash.keys)){ $myHash[$key] = 5 }
There is a much simpler way of achieving this. You cannot change the value of a hashtable while enumerating it because of the fact that it's a reference type variable. It's exactly the same story in .NET.
Use the following syntax to get around it. We are converting the keys collection into a basic array using the @()
notation. We make a copy of the keys collection, and reference that array instead which means we can now edit the hashtable.
$myHash = @{} $myHash["a"] = 1 $myHash["b"] = 2 $myHash["c"] = 3 foreach($key in @($myHash.keys)){ $myHash[$key] = 5 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With