Welcome to OGeek Q&A 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...