1

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
1

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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

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"'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.