使用变量键的 Powershell 哈希表值
Powershell Hashtable values using variable key
我试图让用户进行选择,然后 return 基于该选择的哈希表中的值。
我的哈希表如下所示:
$choices = @{ 0 = "SelectionA";
1 = "SelectionB";
99 = "SelectionC"}
我的选择是这样的:
$selection = Read-Host -Prompt "
Please make a selection
0 - Selection A
1 - Selection B
99 - Selection C "
然后我尝试根据这样的选择取回值:
$choices.$selection
或
$choices.{$selection}
这不起作用。是否可以使用变量作为键来调用哈希表值?
感谢您提供的任何帮助!
您可以使用Get_Item方法。
$myChoice = $choices.Get_Item($selection)
您可能必须先将 $selection 变量转换为整数,因为我相信它会以字符串形式出现。
有关哈希表的更多信息:https://technet.microsoft.com/en-us/library/ee692803.aspx
以上评论均为正确答案。我将它们添加为结束问题的答案。
来自 :
$choices.[int]$selection
或通过:
$choices = @{ '0' = 'SelectionA'}
This is one of the PowerShell's automatic type conversion blindspots. Keys in your hashtable are integers, but Read-Host returns strings.
PSVersion 7中的简单作品
$ha=@{0='aa';1='bb'}
$sel=0
$ha.$sel // 'aa'
我试图让用户进行选择,然后 return 基于该选择的哈希表中的值。
我的哈希表如下所示:
$choices = @{ 0 = "SelectionA";
1 = "SelectionB";
99 = "SelectionC"}
我的选择是这样的:
$selection = Read-Host -Prompt "
Please make a selection
0 - Selection A
1 - Selection B
99 - Selection C "
然后我尝试根据这样的选择取回值:
$choices.$selection
或
$choices.{$selection}
这不起作用。是否可以使用变量作为键来调用哈希表值?
感谢您提供的任何帮助!
您可以使用Get_Item方法。
$myChoice = $choices.Get_Item($selection)
您可能必须先将 $selection 变量转换为整数,因为我相信它会以字符串形式出现。
有关哈希表的更多信息:https://technet.microsoft.com/en-us/library/ee692803.aspx
以上评论均为正确答案。我将它们添加为结束问题的答案。
来自
$choices.[int]$selection
或通过
$choices = @{ '0' = 'SelectionA'}
This is one of the PowerShell's automatic type conversion blindspots. Keys in your hashtable are integers, but Read-Host returns strings.
PSVersion 7中的简单作品
$ha=@{0='aa';1='bb'}
$sel=0
$ha.$sel // 'aa'