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\"] =
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
}
As mentioned in a previous answer, clone
is the way to go. I had a need to replace any null values in a hash with "Unknown" nd this one-liner does the job.
($record.Clone()).keys | %{if ($record.$_ -eq $null) {$record.$_ = "Unknown"}}
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
You have to get creative!
$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3
$keys = @()
[array] $keys = $myHash.keys
foreach($key in $keys)
{
$myHash.Set_Item($key, 5)
}
$myHash
Name Value
---- -----
c 5
a 5
b 5
$myHash = @{
Americas = 0;
Asia = 0;
Europe = 0;
}
$countries = @("Americas", "Asia", "Europe", "Americas", "Asia")
foreach($key in $($myHash.Keys))
{
foreach($Country in $countries)
{
if($key -eq $Country)
{
$myHash[$key] += 1
}
}
}
$myHash
$myHash = @{
Americas = 0;
Asia = 0;
Europe = 0;
}
$countries = @("Americas", "Asia", "Europe", "Americas", "Asia")
foreach($key in $($myHash.Keys))
{
foreach($Country in $countries)
{
if($key -eq $Country)
{
$myHash[$key] += 1
}
}
}
Updating a hash value if array elements matched with a hash key.