1

Below i'm trying to create nested array and to add array elements to it like below

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

And here is the script to get the above structure

 $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)
   }

Inputs I gave for $uinput is 1,3,5,7,9,2,4,6

But the final structure I got through the above script is

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

Suggestions please!

  • 1
    Does this answer your question? [Powershell Multidimensional Arrays](https://stackoverflow.com/questions/9397137/powershell-multidimensional-arrays) – iRon Nov 10 '20 at 07:25
  • 1
    which specific part clarifies my doubt – Django Unchained Nov 10 '20 at 12:30
  • Related: [1](https://stackoverflow.com/questions/1390782/jagged-powershell-array-is-losing-a-dimension-when-only-one-element-exists), [2](https://stackoverflow.com/questions/34698844/multidimensional-arrays-with-only-one-entry), [3](https://superuser.com/questions/414650/why-does-powershell-silently-convert-a-string-array-with-one-item-to-a-string) – ggorlen Mar 21 '23 at 01:02

1 Answers1

0

To force value(s) to be an array, add a comma to the front. The problem (and beauty) of powershell is it is going to try and unwrap those arrays implicitly. You can also collect the output of foreach, Foreach-Object, and For loops directly to a variable. Be sure not to output items with Write-Output that you don't intend to collect/work with - that's what Write-Host is for.

$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: $_
}

Output

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
Doug Maurer
  • 8,090
  • 3
  • 12
  • 13