Return Multidimensional Array From Function

前端 未结 2 1071
后悔当初
后悔当初 2020-12-02 00:56

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,

相关标签:
2条回答
  • 2020-12-02 01:11

    when you declare single line array like

    $array1 = "Apple","Banana"
    

    when you call :

    $array1[0][1]
    

    this will happen :

    this code

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

    exact the same of this:

    $array1 = "Apple","Banana"
    

    but when you declare 2 row of array like :

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

    this will happen :

    if you need apple in your first code just call array[0] not array[0][0]. array[0][0] return char for you.

    sorry for my bad english i hope you understand

    0 讨论(0)
  • 2020-12-02 01:23

    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
    }
    
    0 讨论(0)
提交回复
热议问题