I'm trying to convert text selected from a list into a variable name. this is the testing code I'm using
$trees = @("oak","pine","teak")
$fruit = @("apple","pear","banana")
$color = @("red","green","blue")
function list($items){
foreach ($item in $items){
Write-Host $item
}
}
my goal is something like.
$select = 'color'
so I can use it as a variable, like this.
Write-Host $select # should display 'red green blue'
Write-Host $select[1] # should display 'green'
list($select) # calling the function should display
# red
# green
# blue
this is some of the things i've tried
$select = $'color'
$select = $('color')
$select = -join($'color')
$select = Get-Variable 'color'
$select = Get-Variable(color)
$select = $(Get-Variable 'color')
I'm a complete noob with powershell so Thanks in advance for any help.
Get-VariableandSet-Variablecmdlets, but note that there are usually better alternatives, such as hashtables. See the linked duplicates for details.(Get-Variable $select -ValueOnly)and(Get-Variable $select -ValueOnly)[1][0]on the result isn't spelled out, but that is incidental to the solution), whereas the third duplicate shows preferable alternative techniques that avoid indirection.Write-Hostis typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it by itself; e.g.,$valueinstead ofWrite-Host $value(or useWrite-Output $value, though that is rarely needed). See also: the bottom section of this answer.