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

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

提交回复
热议问题