Nihth
Nihth

Reputation: 3

Output variable value from variable within a variable

Im having trouble outputting the value of a variable name that is in a variable. I have one array that contains the name of several other arrays like this:

>$arrayx1
array00
array01
array02
array03
array10
array11
array12
array13

Each of those arrays have their own value, I want to output that value to a file in a loop. I got the loop and everything else working, except it outputs the name of the arrays and not the arrays value.

$outnr1 = 0
$outnr2 = 0
$null | out-file $path
foreach ($nr3 in $arrayx1) {
    $output = $arrayx1[$outnr2]
    echo "$($output)" | out-file $path -encoding Unicode -append
    $outnr2 = $outnr2 + 1
    if ($outnr2 -gt 3) {
        $outnr1 = $outnr1 + 1
        }
    }        

The file ends up looking like $arrayx1

Upvotes: 0

Views: 237

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

Variable variables (like $$Name in PHP) aren't supported in PowerShell.

Instead, as mentioned in the comments, you should use Get-Variable to retrieve the value of the a variable you have the name of:

foreach($varName in $arrayx1)
{
    $var = Get-Variable -Name $varName -ValueOnly
    $var | Out-File $path -Encoding Unicode -Append
}

I'm not entirely clear on what you're trying to accomplish with the $outnr1 and $outnr2 variables in your original example, but if you want to limit the output to just the first 3 items in $arrayx1, use Select-Object -First:

foreach($varName in $arrayx1 | Select-Object -First 3)
{
    $var = Get-Variable -Name $varName -ValueOnly
    $var | Out-File $path -Encoding Unicode -Append
}

or the range operator:

foreach($varName in $arrayx1[0..2])
{
    $var = Get-Variable -Name $varName -ValueOnly
    $var | Out-File $path -Encoding Unicode -Append
}

Upvotes: 1

Related Questions