【问题标题】:How to get 2 dimensional array with foreach in PowerShell?如何在PowerShell中使用foreach获取二维数组?
【发布时间】:2021-05-25 13:17:27
【问题描述】:

我有二维数组。我想获取数组的每个值。 我试过这个,但是 $Name 中的每个数组都有 $Date 中的所有数组。但我期望 $Name 中的第一项等于 $Date 中的第一项。 这是我的预期结果:

A\11
B\12
C\13

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed

foreach ($na in $Name)
{
     foreach ($dt in $Date)
     {
          $NameAndDate = "$na\$dt"
          Write-Host $NameAndDate
     }
}

但是从上面的代码我得到了这个结果

A\11
A\12
A\13
B\11
B\12
B\13
C\11
C\12
C\13

请大家帮忙。谢谢

【问题讨论】:

  • @iRon 不,它不能回答我的问题
  • 您是否尝试将两个一维数组合并为一个二维数组?
  • @SBR - 您的问题没有完全的意义,“B\13”是否应该存在于您的预期输出中? - 如果是这样,您没有完全声明应该确定什么逻辑,如果不是这种情况,我建议使用 for 循环:For ($i = 0; $i -lt $name.count; $i++){ ($Name[$i]) + "\" + ($Date[$i]) }
  • 请解释您期望的输出。 @jfmilner 答案返回 A\11 B\12 C\13 我猜你实际期望的(以及副本中描述的内容)。但是在您的示例脚本中,您在顶部有A\11 B\12 B\13 C\13,这是您期望的输出吗?如果是,请说明B\13 的来源。

标签: arrays powershell multidimensional-array


【解决方案1】:

试试这个

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed
foreach ($i in 0..($Name.Count -1)) {
    write-host ($Name[$i] + "\" + $Date[$i])
}

【讨论】:

    【解决方案2】:

    当组合两个数组时,两个数组都具有不固定数量的元素,您需要确保索引不会超出任何数组索引。

    这里最简单的方法是使用索引循环,将最大迭代次数设置为数组项的最小数量:

    $Name = "A", "B", "C"    # the size of this array not fixed
    $Date = "11", "12", "13" # the size of this array not fixed
    
    # make sure you do not index beyond any of the array indices
    $maxLoop = [math]::Min($Name.Count, $Date.Count)
    
    for ($i = 0; $i -lt $maxLoop; $i++) {
        # output the combined values
        '{0}\{1}' -f $Name[$i], $Date[$i]
    }
    

    输出:

    A\11
    B\12
    C\13
    

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2015-04-07
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多