1

Let's assume the following Dictonary:

$Grid = [System.Collections.Generic.Dictionary[[System.String],[System.Boolean]]]::new()
For ( $i = 0; $i -lt 10; $i++ ) {
  For ( $j = 0; $j -lt 10; $j++ ) {
    $Grid.Add("$i,$j", $false)
  }
}

That makes a 10x10 "Grid" with some sort of Coordinates:

0,0 = False
0,1 = False
0,2 = False

and so on.

I am able to set a range of them to a specific value:

$Grid['0,0', '0,1', '0,2'] = $true

But i can't get it to work to toggle the actual value.

What i try to accomplish is something like

$Grid['0,0', '0,1', '0,2'] = -Not $_.Value

Any help is highly appreciated! - Thanks in advance!

EDIT:

You're NOT able to assign a value to a range of indices in the way i wrote. Please have a look at this answer from mklement0 for more details.

BaBa
  • 337
  • 2
  • 10
  • Btw, even `$Grid['0,0', '0,1', '0,2'] = $true` does _not_ work for me in PowerShell 7.2 (cannot test in Windows Powershell), and it seems that this is by design: _assigning_ to an indexed expression only works with a _single_ index / key. – mklement0 Dec 03 '21 at 16:29

1 Answers1

4

You'll have to access the entries individually:

'0,0', '0,1', '0,2' | ForEach-Object { $Grid[$_] = -not $Grid[$_] }

The reason is:

  • Using multiple indices / keys using index notation (such as ['0,0', '0,1', '0,2']) only works for getting elements / values, not also for setting.[1]
    (Even if that worked, you wouldn't be able to refer to the target elements' / entries' existing value, and would therefore limit you to assigning the same, fixed value to all targets)

[1] As of PowerShell 7.2, while the error message in response to attempting such an assignment is explicit for arrays (assignment to slices is not supported., leaving aside that the term slices isn't really used in PowerShell), it is confusing for dictionaries (which includes hashtables): Unable to index into an object of type <dictionary-type>. Similarly, attempting to assign to a property of a collection's elements via member-access enumeration - which isn't supported either - results in a confusing error message -see GitHub issue #5271.

mklement0
  • 382,024
  • 64
  • 607
  • 775