0

I have the following code:

$CompletedCount = 0
$ArrayName1 = @('test','test1','test2')
$ArrayName2 = @('test3','test4','test5')
$Array = 0
while($true)
{
    Write-Host $CompletedCount
    $CompletedCount =2
    if ($CompletedCount -gt 0)
        {
            $Array++
            $ArrayToDo = "ArrayName{0}" -f $Array
            Write-Host "Starting with $ArrayToDo"
            foreach ($Name in $ArrayToDo)
            {
                Write-Host $ArrayToDo.Length
                $Name     
            } 
            Start-Sleep -Seconds 5
        }else
        {
            Write-Host "not able to start new batch, sleeping" 
            Start-Sleep -Seconds 10
        }
}

in the line foreach ($Name in $ArrayToDo) I want it to show the values in $ArrayName1 but the only thing it does is print 10 and ArrayName1 . Why doesn't 'fetch' the Array-Variable and show its values?

3
  • If you want to get the value of a variable based on its string name alone, use Get-Variable --> (Get-Variable $ArrayToDo -ValueOnly).Length Commented May 27, 2021 at 19:55
  • @AdminOfThings I want to loop through the array and print its values. the length i'm using just for testing Commented May 27, 2021 at 19:58
  • Because $array todo is just a string. You can use (Get-Variable $arraytodo).value or maybe ${$arraytodo} Commented May 27, 2021 at 20:05

1 Answer 1

2

You want to find a variable's value by only having its string name. When the parser sees $ outside of a string or special circumstance like regex, it interprets the following characters (as long as they are legal variable characters) as the variable name. So if you are not providing the parser with the variable name at the time when $ is parsed (because tokenizing happens before variable substitution), then you need another way. Enter Get-Variable.

$ArrayName1 = @('test','test1','test2')
$ArrayName2 = @('test3','test4','test5')
$Array = 1
while ($Array -le 2) {
    $ArrayToDo = "ArrayName{0}" -f $Array++
    foreach ($name in (Get-Variable $ArrayToDo -ValueOnly)) {
        "A Name in $ArrayToDo"
        $name
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.