4

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}

3 Answers3

3

Consider (probaply) better alternatves:

$Hash=@{Cart="text cart";Cat="text cat";Home="text home"}
$var = [PSCustomObject]$hash

$hash

$var

$names = "Cart","Cat","Home"
foreach ($name in $names){
    "`$hash['{0}']={1}" -f $name,$hash[$name]
    "`$var.{0}={1}" -f $name,$var.$name
}

Sample output:

Name                           Value
----                           -----
Cart                           text cart
Cat                            text cat
Home                           text home

Cart      Cat      Home
----      ---      ----
text cart text cat text home    

$hash['Cart']=text cart
$var.Cart=text cart
$hash['Cat']=text cat
$var.Cat=text cat
$hash['Home']=text home
$var.Home=text home

With this approach(es) you also don't need to know the names beforehand,
you can iterate them with:

$hash.Keys

or

$var.PSObject.Properties.Name
2

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
js2010
  • 23,033
  • 6
  • 64
  • 66
0

You can use Invoke-Expression. This command evaluates a string and runs it as a command. See the Microsoft Docs for detailed information Invoke-Expression.

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

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

Otherwise, as Bacon_Bits suggested, you can use Get-Variable. For this option you need to exclude the $-sign and forward just the name. I selected only the Value, otherwise you get a table with Name and Value.

foreach (...)
{
    $var2="var_{0}" -f $name
    (Get-Variable -Name $variable).Value
}
Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • [`Invoke-Expression` should generally be avoided](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/) – mklement0 Sep 07 '19 at 20:58