哈希表中的解释点
Interpretation point in a hashtable
有一个哈希表:
$Main = @{
One = 'One Value'
Two = @{
Two = 'Two Value'
Tree = @{
Tree = 'Tree Value'
}
}
}
为什么我无法通过这种方式获取值?
# It works
$Want = 'One'
$Main.$Want
# This does not work. I get a void
$Want = 'Two.Two'
$Main.$Want
# And that of course doesn't work either
$Want = 'Two.Tree.Tree'
$Main.$Want
如何修改 $Want
字符串,使其成为可能(例如,[Something]$Want = 'Two.Tree.Tree'
,我得到 Tree Value
的值 $Main.$Want
)。
此刻,我做出了这样的决定。但可以肯定的是,提供了更短更快的解决方案。
$Main = @{
One = 'One Value'
Two = @{
Two = 'Two Value'
Tree = @{
Tree = 'Tree Value'
}
}
}
# $Want = 'One'
# $Want = 'Two.Two'
$Want = 'Two.Tree.Tree'
$Want = $Want -Split '\.'
$Want = Switch ( $Want.Length ) {
1 { $Main.($Want[0]) }
2 { $Main.($Want[0]).($Want[1]) }
3 { $Main.($Want[0]).($Want[1]).($Want[2]) }
}
$Want
# Result 'Tree Value'
使用调用表达式:
$Want = 'Two.Two'
Invoke-Expression ('$Main.' + $Want)
有一个哈希表:
$Main = @{
One = 'One Value'
Two = @{
Two = 'Two Value'
Tree = @{
Tree = 'Tree Value'
}
}
}
为什么我无法通过这种方式获取值?
# It works
$Want = 'One'
$Main.$Want
# This does not work. I get a void
$Want = 'Two.Two'
$Main.$Want
# And that of course doesn't work either
$Want = 'Two.Tree.Tree'
$Main.$Want
如何修改 $Want
字符串,使其成为可能(例如,[Something]$Want = 'Two.Tree.Tree'
,我得到 Tree Value
的值 $Main.$Want
)。
此刻,我做出了这样的决定。但可以肯定的是,提供了更短更快的解决方案。
$Main = @{
One = 'One Value'
Two = @{
Two = 'Two Value'
Tree = @{
Tree = 'Tree Value'
}
}
}
# $Want = 'One'
# $Want = 'Two.Two'
$Want = 'Two.Tree.Tree'
$Want = $Want -Split '\.'
$Want = Switch ( $Want.Length ) {
1 { $Main.($Want[0]) }
2 { $Main.($Want[0]).($Want[1]) }
3 { $Main.($Want[0]).($Want[1]).($Want[2]) }
}
$Want
# Result 'Tree Value'
使用调用表达式:
$Want = 'Two.Two'
Invoke-Expression ('$Main.' + $Want)