【问题标题】:How to create nested array and to add array elements in it?如何创建嵌套数组并在其中添加数组元素?
【发布时间】:2020-11-10 05:29:57
【问题描述】:

下面我正在尝试创建嵌套数组并向其中添加数组元素,如下所示

$nArr = @(@('1','3'), @('5','7','9'), @('2','4','6'))

这是获取上述结构的脚本

 $integ = @(2,3,3)

$nArr = ,@()
$nArr1 = @()
foreach ($pd in $integ) {
    for($i=0;$i -lt $pd;$i = $i+1) {
    $uinput= Read-Host -Prompt "Assign the pod numbers for"
    Write-Output `n
    $nArr1 += [array]$uinput
    }
    $nArr += @($nArr1)
   }

我为$uinput 提供的输入是1,3,5,7,9,2,4,6

但是我通过上面的脚本得到的最终结构是

$nArr = @('1','3','5','7','9','2','4','6')

请提出建议!

【问题讨论】:

标签: powershell powershell-2.0 powershell-3.0 powershell-4.0 powercli


【解决方案1】:

要将值强制为数组,请在前面添加一个逗号。 powershell 的问题(和优点)是它会尝试隐式地解开这些数组。您还可以将foreachForeach-ObjectFor 循环的输出直接收集到一个变量中。确保不要输出您不打算收集/使用的带有Write-Output 的项目——这就是Write-Host 的用途。

$integ = @(2,3,3)

$nArr = foreach ($pd in $integ)
{
    $nArr1 = for($i=0;$i -lt $pd;$i = $i+1) {
        Read-Host -Prompt "Assign the pod numbers for"
        Write-Host `n
    }
    ,$nArr1
}

$nArr | ForEach-Object {
    Write-Host Object type: $_.gettype().BaseType.name
    Write-Host Member count: $_.count
    write-host Values: $_
}

输出

Object type: Array
Member count: 2
Values: 1 3
Object type: Array
Member count: 3
Values: 5 7 9
Object type: Array
Member count: 3
Values: 2 4 6

【讨论】:

  • 我没有看到 Values 是空的
  • 不知道你是怎么做到的。 imgur.com/JIlAsuj
  • 我在 ISE imgur.com/BNy9F0K 中将其作为 .ps1 脚本执行
  • 哦,我明白了,您将读取主机分配给变量,删除它。
  • 是的,但在 powershell 中很难看到它。我们已经确认有 3 个元素,其中第一个有 2 个值,另外两个有 3 个值。
猜你喜欢
  • 2022-01-19
  • 2022-01-25
  • 2023-04-05
  • 1970-01-01
  • 2013-02-04
  • 2019-03-09
  • 1970-01-01
  • 2018-04-26
  • 2016-06-07
相关资源
最近更新 更多