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

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

提交回复
热议问题