Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0powercli

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


I have a nested array @(@('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: $_
}

Here is the output for the above block:

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
    

I'm trying to concatenate Port Group- to the values in a nested array using the below code

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

Above code produces the output as:

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

I wanted the output as, @(@('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

How to fulfill my objective?


Solution

  • I have such a proposal

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

    output: enter image description here