Powershell: Multidimensional array as return value of function Powershell: Multidimensional array as return value of function powershell powershell

Powershell: Multidimensional array as return value of function


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


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-HostReturn $Return}#End Function$GetItOut = My-FunctionWrite-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.ComputerIf ($var1 –like “True”){write-host “Its True, Its True”}