PowerShell HashTable - 初始化期间的自引用
PowerShell HashTable - self referencing during initialization
我有一个理论上的问题 - 如何在初始化期间引用散列 table,例如,根据其他已经声明的成员计算一个成员。
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
有什么办法吗?真的可以吗?
编辑:
这是我的解决方案:
$myHashTable =
@{
One = 1
Two= 2
}
$myHashTable.Three = $myHashTable.One + $myHashTable.Two
恐怕使用对象初始化语法是不可能的。虽然可以使用变量,但您必须在创建对象之前计算值。
我不推荐这样做,但您可以将初始化程序迭代两次或更多次:
(0..1) | %{
$a = @{
One = 1
Two = $a.One + 1
}
}
(0..2) | %{
$b = @{
One = 1
Two = $b.One + 1
Three = $b.Two + 1
}
}
确保所有计算都是幂等的,即不依赖于迭代次数。
你也可以重温这个...
有时哈希表很长
并且只能在 2 或 3 次重复中定义...
工作正常:
$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
我有一个理论上的问题 - 如何在初始化期间引用散列 table,例如,根据其他已经声明的成员计算一个成员。
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
有什么办法吗?真的可以吗?
编辑: 这是我的解决方案:
$myHashTable =
@{
One = 1
Two= 2
}
$myHashTable.Three = $myHashTable.One + $myHashTable.Two
恐怕使用对象初始化语法是不可能的。虽然可以使用变量,但您必须在创建对象之前计算值。
我不推荐这样做,但您可以将初始化程序迭代两次或更多次:
(0..1) | %{
$a = @{
One = 1
Two = $a.One + 1
}
}
(0..2) | %{
$b = @{
One = 1
Two = $b.One + 1
Three = $b.Two + 1
}
}
确保所有计算都是幂等的,即不依赖于迭代次数。
你也可以重温这个...
有时哈希表很长
并且只能在 2 或 3 次重复中定义...
工作正常:
$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