PowerShell - 将计数器附加到数组变量并在之后使用它

PowerShell - Append counter to Array variable and use it after

我有以下代码:

$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
        }
}

foreach ($Name in $ArrayToDo) 行中,我希望它显示 $ArrayName1 中的值,但它唯一做的就是打印 10 和 ArrayName1 。为什么 'fetch' 数组变量不显示它的值?

您想仅通过变量的字符串名称来查找变量的值。当解析器在字符串之外看到 $ 或像正则表达式这样的特殊情况时,它会将后面的字符(只要它们是合法的变量字符)解释为变量名。因此,如果您在解析 $ 时没有向解析器提供变量名(因为标记化发生在变量替换之前),那么您需要另一种方法。输入 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
    }
}