Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Multidimensional array as return value of function

I've got some problems with two-dimensional arrays in PowerShell. Here's what I want to do:

I create a function that is supposed to return a two-dimensional array. When invoking the function I want the return value to be a new two-dimensional array.

For a better understanding I've added an example function, below:

function fillArray() {
    $array = New-Object 'object[,]' 2,3

    $array[0,0] = 1
    $array[0,1] = 2
    $array[0,2] = 3

    $array[1,0] = 4
    $array[1,1] = 5
    $array[1,2] = 6

    return $array
}
$erg_array = New-Object 'object[,]' 2,3
$erg_array = fillArray

$erg_array[0,1] # result is 1 2
$erg_array[0,2] # result is 1 3
$erg_array[1,0] # result is 2 1

The results are not what I expect. I want to return the information in the same way as declared in the function. So I would expect $erg_array[0,1] to give me 2 instead of the 1,2 I receive with the code above. How can I achieve this?

like image 487
casheeew Avatar asked Oct 20 '11 08:10

casheeew


2 Answers

In order to return the array exactly as it is without "unrolling" use the comma operator (see help about_operators)

function fillArray() {
    $array = New-Object 'object[,]' 2, 3

    $array[0,0] = 1
    $array[0,1] = 2
    $array[0,2] = 3

    $array[1,0] = 4
    $array[1,1] = 5
    $array[1,2] = 6

    , $array # 'return' is not a mistake but it is not needed
}

# get the array (we do not have to use New-Object now)
$erg_array = fillArray

$erg_array[0,1] # result is 2, correct
$erg_array[0,2] # result is 3, correct
$erg_array[1,0] # result is 4, correct

The , creates an array with a single item (which is our array). This 1-item array gets unrolled on return, but only one level, so that the result is exactly one object, our array. Without , our array itself is unrolled, its items are returned, not the array. This technique with using comma on return should be used with some other collections as well (if we want to return a collection instance, not its items).

like image 134
Roman Kuzmin Avatar answered Sep 20 '22 09:09

Roman Kuzmin


What is really missing in this port is what everyone is looking for. How to get more than one thing out of a function. Well I am going to share what everyone wants to know who has searched and found this hoping it will answer the question.

function My-Function([string]$IfYouWant)
{
[hashtable]$Return = @{} 

$Return.Success = $False
$Return.date = get-date
$Return.Computer = Get-Host

Return $Return
}
#End Function

$GetItOut = My-Function
Write-host “The Process was $($GetItOut.Success) on the date $($GetItOut.date) on the     host     $($GetItOut.Computer)”

#You could then do
$var1 = $GetItOut.Success
$Var2 =$GetItOut.date
$Var3 = $GetItOut.Computer

If ($var1 –like “True”){write-host “Its True, Its True”}
like image 3
Peter S Avatar answered Sep 19 '22 09:09

Peter S