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

后端 未结 10 1603
清歌不尽
清歌不尽 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:40

    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
    }
    
    0 讨论(0)
  • 2020-12-29 02:42

    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"}}
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-29 02:48

    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
    
    0 讨论(0)
  • 2020-12-29 02:56
    $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
    
    0 讨论(0)
  • 2020-12-29 02:57
    $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.

    0 讨论(0)
提交回复
热议问题