PowerShell HashTable - self referencing during initialization PowerShell HashTable - self referencing during initialization powershell powershell

PowerShell HashTable - self referencing during initialization


This won't be possible using the object initializer syntax I'm afraid. While it is possible to use variables, you'll have to compute the values before creating the object.


I cannot recommend this, but you can iterate the initializer 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 all calculations are idempotent, i.e. do not depend on a number of iterations.


You can also recur to this...

sometimes when the hashtable is very long
and can be defined only in 2 or three recurrences...
works fine:

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

    but now... we can refer the items
    in first part of the hashtable