Powershell Hashtable values using variable key
Asked Answered
R

3

6

I am trying to let a user make a selection and then return a value from a hashtable based on that selection.

My hashtable looks like this:

$choices = @{ 0 = "SelectionA"; 
              1 = "SelectionB"; 
              99 = "SelectionC"}

My selection looks like this:

$selection = Read-Host -Prompt "
Please make a selection
0 - Selection A
1 - Selection B
99 - Selection C "

Then I'm trying to bring back the value based on the selection like this:

$choices.$selection

or

$choices.{$selection}

This isn't working. Is it possible to call a hashtable value using a variable as the key?

Thanks for any help you can offer!

Raindrop answered 5/4, 2016 at 20:30 Comment(2)
$choices.[int]$selectionTrevelyan
Or $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.Disk
R
0

The comments above are both correct answers. I'm adding them as answers to close the question.

By PetSerAl:

$choices.[int]$selection

Or by beatcracker:

$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.

Raindrop answered 15/5, 2017 at 15:39 Comment(0)
B
6

You can use the Get_Item method.

$myChoice = $choices.Get_Item($selection)

You may have to convert the $selection variable into an integer first, since I believe it will come in as a string.

More info on hash tables: https://technet.microsoft.com/en-us/library/ee692803.aspx

Belostok answered 5/4, 2016 at 21:3 Comment(0)
R
0

The comments above are both correct answers. I'm adding them as answers to close the question.

By PetSerAl:

$choices.[int]$selection

Or by beatcracker:

$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.

Raindrop answered 15/5, 2017 at 15:39 Comment(0)
B
-1

The simple works in PSVersion 7

$ha=@{0='aa';1='bb'}
$sel=0
$ha.$sel // 'aa'
Bradford answered 4/7, 2021 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.