【问题标题】:PowerShell - Append counter to Array variable and use it afterPowerShell - 将计数器附加到数组变量并在之后使用它
【发布时间】:2021-08-16 02:50:01
【问题描述】:

我有以下代码:

$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 。为什么不“获取”数组变量并显示其值?

【问题讨论】:

  • 如果要单独根据字符串名称获取变量的值,请使用Get-Variable --> (Get-Variable $ArrayToDo -ValueOnly).Length
  • @AdminOfThings 我想遍历数组并打印它的值。我仅用于测试的长度
  • 因为 $array todo 只是一个字符串。您可以使用 (Get-Variable $arraytodo).value 或者 ${$arraytodo}

标签: arrays powershell variables dynamic concatenation


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多