Search code examples
powershellindirection

PowerShell - How do I call a variable with another variable?


I have this code:

$var_Cart="text cart"
$var_Cat="text cat"
$var_Home="text home"

$names = "Cart","Cat","Home"
foreach ($name in $names)
{
    $variable="var_$name"
    Write-Host "`n`-----Print "$variable"-----"
}

how can i get to print "text cart, text cat and text home"?

NOTE: In BASH resolve like this: ${!var}


Solution

  • Using the value property of get-variable:

    $var_Cart = 'text cart'
    $var_Cat = 'text cat'
    $var_Home = 'text home'
    
    $names = 'Cart','Cat','Home'
    foreach ($name in $names)
    {
      (get-variable var_$name).value
    }
    

    output

    text cart
    text cat
    text home