Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

powershell - Return Multidimensional Array From Function

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...