Return Multidimensional Array From Function
arrays, multidimensional-array, powershell
Solution
PowerShell unrolls arrays returned from a function. Prepend the returned array with the comma operator (`,`, unary array construction operator) to wrap it in another array, which is unrolled on return, leaving the nested array intact.
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
return ,$array1
}
Problem
I encountered some issue in converting my existing vbs script to PowerShell script. I have illustrate here with some dummy codes instead of my original code. In example 1, I only have 1 set of elements in the array, upon return the array variable to the function, it will only display P. However in example 2, where I have 2 set of elements in the array, upon return the array variable to the function, it will display the elements properly. If you print the array inside the function in example 1 and 2. There isn't any issue in getting the results. I have googled and not able to find any solution to it. Many thanks in advance for the kind help. Example 1: ``` function testArray { $array1 = @() $array1 += ,@("Apple","Banana") return $array1 } $array2 = testArray Write-Host $array2[0][1] ``` Result is "P". Example 2: ``` function testArray { $array1 = @() $array1 += ,@("Apple","Banana") $array1 += ,@("Orange","Pineapple") return $array1 } $array2 = testArray Write-Host $array2[0][0] ``` Result is "Apple".