Search code examples
powershellinitializationhashtable

PowerShell HashTable - self referencing during initialization


I have a theoretical problem - how to reference a hash table during its initialization, for example, to compute a member based other already stated members.

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 it? Is it actually possible?

Edit: This was my solution:

$myHashTable = 
@{
    One = 1
    Two= 2
}
$myHashTable.Three = $myHashTable.One + $myHashTable.Two

Solution

  • 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