boomie
boomie

Reputation: 13

Replace values in hashtable in PowerShell

I have a hashtable in PowerShell that looks like this:

$table = @{
     1 =  3;
     2 =  3;
     5 =  6;
    10 = 12;
    30 =  3
}

I need to replace all "3" values with "4".

  1. Is there a nice and clean way to do this without iterating over each pair and writing each one to a new hashtable?
  2. Could the action with the same data be done easier if I'd use some other .NET collection class?

This throws exception that "Collection was modified":

$table.GetEnumerator() | ? {$_.Value -eq 3} | % { $table[$_.Key]=4 }

This adds another "Values" member to the object and breaks it:

$table.Values = $table.Values -replace 3,4

Upvotes: 1

Views: 17260

Answers (2)

Chris
Chris

Reputation: 195

The above answer didn't work for me and I couldn't fit this as a comment. The above single-lined answer didn't do anything. I am trying to change a single value to "Off" based on my hashtable.Key aka Name. Notice where I wrote $(backtick) is supposed to be a literal backtick, but it was messing up the code block. Here is my hashtable that is pulled from .\BeepVariables.txt.

Name                    Value
----                    ----
$varAwareCaseSound       "On"
$varEmailSound           "On"
function SetHash2([string]$keyword, [string]$value){
   $hash = @{}
   $hash = (get-content .\BeepVariables.txt).replace(";"," $(backtick) n") | ConvertFrom-StringData
   @($hash.GetEnumerator()) | ?{$_.key -like "*$keyword*"} | %{$hash[$_.value]=$value}
   $hash
}
SetHash2 "aware" '"Off"'

Upvotes: 0

Duncan
Duncan

Reputation: 95652

You can't modify the table while iterating over it, so do the iteration first and then do the updates. Just split your pipeline in two:

PS>$change = $table.GetEnumerator() | ? {$_.Value -eq 3}
PS>$change | % { $table[$_.Key]=4 }
PS>$table

Name                           Value
----                           -----
30                             4
10                             12
5                              6
2                              4
1                              4

Upvotes: 2

Related Questions