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

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

    I'm new to PowerShell, but I'm quite a fan of using in-built functions, because I find it more readable. This is how I would tackle the problem, using GetEnumerator and Clone. This approach also allows one to reference to the existing hash values ($_.value) for modifying purposes.

    $myHash = @{}
    $myHash["a"] = 1 
    $myHash["b"] = 2
    $myHash["c"] = 3
    
    $myHash.Clone().GetEnumerator() | foreach-object {$myHash.Set_Item($_.key, 5)}
    

提交回复
热议问题