Home > other >  Powershell: Passing a `Read-Host` as the key to HastTable
Powershell: Passing a `Read-Host` as the key to HastTable

Time:02-01

I am trying to pass user input to hashTable, which I am attempting to do.

$someHash = 
@{
    1 = "one";
    2 = "two";
    3 = "three"
 }
 $x = Read-Host "enter 1,2,3"
 Write-Output($someHash.$x) 

For some reason $someHash.$x and $someHash[$x] return null, but $x has it value.

I also can get values out of the map when I hard code keys. Not sure what I am doing incorrectly.

Adding to address comments. I have also tried casting with the same result.

$someHash.[int]$x 
$someHash[[int]$x]
[int]$x = Read-Host "enter 1,2,3"

I have also used strings as keys using single and double-quotes. Same outcome.

CodePudding user response:

Using string keys you won't have a need to convert the result of Read-Host to int.

Note, if below doesn't work, it's most likely because $x was type constrained before ([int]$x), use Remove-Variable x or restart your PowerShell session.

$someHash =
@{
    '1' = "one";
    '2' = "two";
    '3' = "three"
}
$x = Read-Host "enter 1,2,3"
$someHash[$x] # => Works (Recommended)
$someHash.$x  # => Works

Using int keys you would need to type constrain the result of Read-Host to int:

$someHash =
@{
    1 = "one";
    2 = "two";
    3 = "three"
}
[int]$x = Read-Host "enter 1,2,3"
$someHash[$x] # => Works (Recommended)
$someHash.$x  # => Works
  •  Tags:  
  • Related