0

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

1
  • 1
    To get variable by name you should use Get-Variable cmdlet. Commented Jan 13, 2016 at 13:34

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that solved it! Im going to use the $outnr1 and $outnr2 to set line breaks in the file that is being written to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.