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\"] =
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
}