You need to enable JavaScript to run this app. PowerShell拼接计数器生成数组变量名后无法读取值如何解决
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell拼接计数器生成数组变量名后无法读取值如何解决

问题原因

  • 你的$ArrayToDo变量存储的是纯字符串"ArrayName1",并非预先定义的$ArrayName1数组本身,所有后续操作都是针对这个字符串执行:
    • 输出的数值10是字符串"ArrayName1"的字符长度
    • foreach遍历字符串时,PowerShell默认将其识别为单个对象,因此只会输出整个字符串,不会读取到对应数组的元素值

解决方法

方法1:动态读取变量值(最小改动适配现有代码)

使用Get-Variable命令根据字符串形式的变量名,获取对应变量的实际值,仅需修改foreach前后的逻辑即可:

$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"
            # 新增该行,通过变量名字符串获取实际数组
            $targetArray = Get-Variable -Name $ArrayToDo -ValueOnly
            foreach ($Name in $targetArray)
            {
                Write-Host $targetArray.Length
                $Name     
            } 
            Start-Sleep -Seconds 5
        }else
        {
            Write-Host "not able to start new batch, sleeping" 
            Start-Sleep -Seconds 10
        }
}

方法2:哈希表存储多组数组(更规范的实现)

用哈希表统一收纳所有数组,通过键值直接读取目标数组,避免动态变量带来的可读性、维护性问题:

$CompletedCount = 0
# 用哈希表存储所有待遍历数组
$arrayCollection = @{
    1 = @('test','test1','test2')
    2 = @('test3','test4','test5')
}
$Array = 0
while($true)
{
    Write-Host $CompletedCount
    $CompletedCount =2
    if ($CompletedCount -gt 0)
        {
            $Array++
            Write-Host "Starting with ArrayName$Array"
            # 直接读取对应数组
            $targetArray = $arrayCollection[$Array]
            foreach ($Name in $targetArray)
            {
                Write-Host $targetArray.Length
                $Name     
            } 
            Start-Sleep -Seconds 5
        }else
        {
            Write-Host "not able to start new batch, sleeping" 
            Start-Sleep -Seconds 10
        }
}

内容的提问来源于stack exchange,提问作者Kahn Kah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 04:15:04