1

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.

6
  • What you're looking for is variable indirection, where you refer to a variable indirectly, via its name stored in a different variable or provided by an expression. PowerShell enables this via the Get-Variable and Set-Variable cmdlets, but note that there are usually better alternatives, such as hashtables. See the linked duplicates for details. Commented Aug 18, 2023 at 15:33
  • Applied to your example: (Get-Variable $select -ValueOnly) and (Get-Variable $select -ValueOnly)[1] Commented Aug 18, 2023 at 15:35
  • Thanks for your fast reply. The 'similar questions' didn't help any but your answer was exactly what i needed, I was heading the right direction I had never heard of 'Indirection'. I'm 13 year old and I've only been using powershell for about 2 weeks. This is what i've done with it $select = "color" $sel = (Get-Variable $select -ValueOnly) # they all work as i wanted Write-Host $sel Write-Host $sel[1] list($sel) Commented Aug 18, 2023 at 16:29
  • Glad to hear it, @ian. Note that the first two linked duplicates do show the same techniques that I summarized in my comment (except that the use of [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. Commented Aug 18, 2023 at 16:48
  • 1
    As an aside: Write-Host is 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., $value instead of Write-Host $value (or use Write-Output $value, though that is rarely needed). See also: the bottom section of this answer. Commented Aug 18, 2023 at 16:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.