如何在 powershell 中将字符串连接到嵌套数组内的值?

How to concatenate a string to values inside a nested array in powershell?

我有一个嵌套数组@(@('1','3'), @('5','7','9'), @('2','4','6'))

$podnumbers = (3,2,2)
$buffer = 0
$podNarr = foreach ($pd in $podnumbers) {
    $podNarr1 = for($i=0;$i -lt $pd;$i = $i+1) {
      Read-Host -Prompt "Assign the pod numbers"
    }
    ,$podNarr1
    $buffer = $buffer + 1
   }

$podNarr | 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: 2 4 6
Object type: Array
Member count: 3
Values: 5 7 9
    

我正在尝试使用以下代码将 端口组- 连接到嵌套数组中的值

$port = "Port Group-"
$portarr = $podNarr | ForEach-Object {
      $port + $_
    }
Write-Output `n
$portarr | ForEach-Object {
    Write-Host Values: $_
}

以上代码产生的输出为:

Values: Port Group-1 3
Values: Port Group-2 4 6
Values: Port Group-5 7 9

我希望输出为,@(@('Port Group-1','Port Group-3'),@('Port Group-5','Port Group-7','Port Group-9'), @('Port Group-2','Port Group-4','Port Group-6'))

Values: Port Group-1 Port Group-3
Values: Port Group-2 Port Group-4 Port Group-6
Values: Port Group-5 Port Group-7 Port Group-9

如何完成我的objective?

您需要两个 for 循环。一个循环遍历外部数组,而后者循环遍历嵌套数组。 foreach 不行,因为迭代和更改数组是互斥的操作。

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

# Here we traverse through the outer elements
for($a = 0; $a -lt $arr.length; ++$a) {

    # Process each nested array and update its value    
    for($b = 0; $b -lt $arr[$a].length; ++$b) {
        $arr[$a][$b] =  $("Port group-{0} "-f $arr[$a][$b])
    }
}

# Output
$arr | ForEach-Object {
    Write-Host Object type: $_.gettype().BaseType.name
    Write-Host Member count: $_.count
    Write-Host Values: $_
}

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

我有这样的提议

@(@('1','3'), @('5','7','9'), @('2','4','6')) | foreach{
"Values: " + ($_|foreach{"Port Group-$_"})  
}

输出:

如果您不强制输出成为数组,Powershell 会解包数组。 您可以通过在它前面加上一个将数组包裹在另一个 1 元素数组中的一元逗号来强制执行此操作。当该部分被展开时,原始数组将被保留。

类似

$a = @(@('1','3'), @('5','7','9'), @('2','4','6'))
$b = $a | ForEach-Object {
    $c = foreach ($port in $_) { 'Port Group-{0}' -f $port }
    # output this array as ARRAY by wrapping it in a 1-element new array using the unary comma
    ,$c
}


Write-Host $b[0]
Write-Host $b[1]
Write-Host $b[2]

输出

Port Group-1 Port Group-3
Port Group-5 Port Group-7 Port Group-9
Port Group-2 Port Group-4 Port Group-6