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!

2
  • 1
    $choices.[int]$selection Commented Apr 5, 2016 at 20:38
  • 1
    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. Commented Apr 5, 2016 at 20:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-1

The simple works in PSVersion 7

$ha=@{0='aa';1='bb'}
$sel=0
$ha.$sel // 'aa'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.