ian
ian

Reputation: 11

How can I convert text into a variable name in powershell

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.

Upvotes: 1

Views: 151

Answers (0)

Related Questions