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

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

    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
    }
    

提交回复
热议问题