Return multidimensional array from function

I ran into some problem when converting existing vbs script to PowerShell script. I have illustrated several dummy codes here instead of my source code. In example 1, I have only one set of elements in the array, after returning the array variable to the function, it displays only P.

However, in Example 2, where I have 2 sets of elements in the array, after returning the array variable to the function, it displays the elements correctly.

If you print an array inside a function in examples 1 and 2. There is no problem getting the results.

I have googled and not able to find any solution. Thanks a lot in advance for your kind help.

Example 1:

function testArray { $array1 = @() $array1 += ,@("Apple","Banana") return $array1 } $array2 = testArray Write-Host $array2[0][1] 

The result is "P".

Example 2:

 function testArray { $array1 = @() $array1 += ,@("Apple","Banana") $array1 += ,@("Orange","Pineapple") return $array1 } $array2 = testArray Write-Host $array2[0][0] 

The result is Apple.

+5
source share
2 answers

PowerShell expands the arrays returned by the function. Prepare the returned array using the comma operator (,, the unary array construction operator) to wrap it in another array that expands upon return, leaving the nested array intact.

 function testArray { $array1 = @() $array1 += ,@("Apple","Banana") return ,$array1 } 
+6
source

when you declare a single linear array like

 $array1 = "Apple","Banana" 

when you call:

 $array1[0][1] 

it will happen:

enter image description here

this code

 function testArray { $array1 = @() $array1 += ,@("Apple","Banana") return $array1 } $array2 = testArray Write-Host $array2[0][1] 

same:

 $array1 = "Apple","Banana" 

but when you declare 2 lines of an array like:

 function testArray { $array1 = @() $array1 += ,@("Apple","Banana") $array1 += ,@("Orange","Pineapple") return $array1 } $array2 = testArray Write-Host $array2[0][0] 

it will happen:

enter image description here

If you need an apple in your first code, just call the array [0] not array [0] [0]. array [0] [0] returns a char for you.

Sorry for my bad english, I hope you understand

+1
source

Source: https://habr.com/ru/post/1258715/


All Articles