PowerShell HashTable - self-binding during initialization

I have a theoretical problem - how to refer to a hash table during its initialization, for example, to calculate members based on other members already declared.

Remove-Variable myHashTable -ErrorAction Ignore $myHashTable = @{ One = 1 Two= 2 Three = ??? # following expressions do not work # $This.One + $This.Two or # $_.One + $_.Two # $myHashTable.One + $myHashTable.Two # ???? } $myHashTable.Three -eq 3 # make this $true 

Any ideas how to do this? Is it possible?

Edit: This was my solution:

 $myHashTable = @{ One = 1 Two= 2 } $myHashTable.Three = $myHashTable.One + $myHashTable.Two 
+7
source share
3 answers

This will not be possible using the initializer syntax of the object I'm afraid of. Although you can use variables, you will need to calculate the values ​​before creating the object.

+6
source

I cannot recommend this, but you can repeat the initialization twice or more:

 (0..1) | %{ $a = @{ One = 1 Two = $a.One + 1 } } (0..2) | %{ $b = @{ One = 1 Two = $b.One + 1 Three = $b.Two + 1 } } 

Make sure that all calculations are idempotent, that is, independent of the number of iterations.

+2
source

You can also return to this ...

sometimes when the hash table is very long
and can only be determined in 2 or three repetitions ...
works great:

 $AAA = @{ DAT = "C:\MyFolderOfDats" EXE = "C:\MyFolderOfExes" } $AAA += @{ Data = $AAA.DAT + "\#Links" Scripts = $AAA.EXE + "\#Scripts" ScriptsX = $AAA.EXE + "\#ScriptsX" } 
  • Please note that in the second part we just add (+ =)
    more items to the first part ...

    but now ... we can refer to objects
    in the first part of the hash table
0
source

All Articles