1

I know the following is probably not the most efficient code in the world but its how I thought of solving the issue through my own volition.

I'd like to do the following:

 $1 = "Mazada"
 $2 = "Toyota"
 $3 = "Mitsubishi"

$car = Read-Host "Type Variable here" 

Write-Output = $car

Now the final product would give you a list of the variables in "Read-Host" command and then you would know what to type in. I know I have to solve that problem for those of you noticing the missing ingredients in the script.

Ideally I would like for anyone to type in the car choice like "$3" in the Read-Host portion and then assign it to the $car variable so that it outputs Mitsubishi.

What am I doing wrong ?

If I type in $3 i just get = $3

Thank you very much

2
  • Your question doesn't make any sense. What is your end-goal? Commented Apr 9, 2018 at 17:53
  • end-goal is to assign $car a car name by getting the variable from "Read-Host". So if Bob runs the script and he types $2 then $car = $2 so Write-Output = Toyota Commented Apr 9, 2018 at 17:57

1 Answer 1

2

$3 in the context of a running script is an expression that needs to be evaluated by powershell in order to return the variable's value.

When you use Read-Host, powerhsell will not evaluate what was entered as an expression, it just copies the characters into a string. However, it is possible to get the result you desire, using Invoke-Expression, but that is dangerous. You can have the user just enter the name of the variable and use the Get-Variable commandlet:

$1 = "Mazada"
$2 = "Toyota"
$3 = "Mitsubishi"

$var = Read-Host "Type Variable here name here" 

$car = get-Variable -name $var -valueonly

Write-Output "`$car=$car"

A better option would be to present the user with a menu of options that they choose from (e.g. 1, 2 or 3). For example (some error handling missing):

$cars = @("Mazada", "Toyota", "Mitsubishi")

$menuIndex = 1
Write-Host "Choose one of these cars:"
$cars | foreach {
    Write-Host $menuIndex " - $_";
    $menuIndex += 1;
 }


$ChosenItem = [int](Read-Host "Your choice (1 to $($menuIndex-1))")

$car = $cars[$ChosenItem-1]

Write-Output "`$car=$car"
Sign up to request clarification or add additional context in comments.

3 Comments

A safer method would be Get-Variable -Name $var.Replace('$','')
Also, $($_) this syntax is unnecessary.
@TheIncorrigible1: You're right. Updated the answer.

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.