Is there a way to generate a Hashtable that uses properties just defined in the hashtable to create the next property down the line? I know I can just do it line by line instead, but I would like to maintain the formatting I currently have as I like how it reads.
$RequestedSpace = @{}
$RequestedSpace.Clear()
$RequestedSpace = @{
Gb = (Read-Host "How much space (in Gb) would you like left over?")
b = $RequestedSpace.Gb * 1Gb
};
$RequestedSpace.Gb
$RequestedSpace.b
The above results in a null value for $RequestedSpace.b
The below works, but is significantly uglier IMO
$RequestedSpace = @{}
$RequestedSpace.Clear()
$RequestedSpace.Gb = Read-Host "How much space (in Gb) would you like left over?"
$RequestedSpace.b = [bigint]$RequestedSpace.Gb * 1gb
You can take advantage of the fact that:
you can define an auxiliary variable and use the assignment as an expression by enclosing it in (...)
, the grouping operator, which passes the assigned value through
entries are defined in sequence, so subsequent entries can refer to aux. variables defined earlier.
@{
# Note the *definition* of aux. variable $gb
Gb = ($gb = [double] (Read-Host "How much space (in Gb) would you like left over?"))
# Note the *use* of $gb
b = $gb * 1Gb
}
Assuming you enter 2
when prompted, you'l get the following display output:
Name Value
---- -----
Gb 2
b 2147483648
Note:
The technique works for hashtable literals, as shown above (@{ ... }
), as well as [pscustomobject]
literals ([pscustomobject] @{ ... }
).
GitHub suggestion #13782 looks for a built-in way to allow hashtable entries to reference one another.