Lexxy
Lexxy

Reputation: 477

PowerShell multidimensional Array issue

Im creating multidimensional array

cls
$b=[Collections.ArrayList]::new()
$a=4,5,6
[void]$b.Add($a)
$a1=7,8,9
[void]$b.Add($a1)

"Value is: "+$b[0][1]+" ."
"Size  is: "+$b.Count+" ."
""###
function arr(){
    $b=[Collections.ArrayList]::new()
    $a=4,5,6
    [void]$b.Add($a)
    $a1=7,8,9
    [void]$b.Add($a1)
    return $b
}
$c=arr
"Value is: "+$c[0][1]+" ."
"Size  is: "+$c.Count+" ."

Output:

Value is: 5 .
Size  is: 2 .

Value is: 5 .
Size  is: 2 .

Now all is correct. Function return the array in original state, without any deformations. But I cant know beforehand array size, and when size of array is 1, i get next problem:

cls
$b=[Collections.ArrayList]::new()
$a=4,5,6
[void]$b.Add($a)

"Value is: "+$b[0][1]+" ."
"Size  is: "+$b.Count+" ."
""###
function arr(){
    $b=[Collections.ArrayList]::new()
    $a=4,5,6
    [void]$b.Add($a)
    return $b
}
$c=arr
"Value is: "+$c[0][1]+" ."
"Size  is: "+$c.Count+" ."

Output:

Value is: 5 .
Size  is: 1 .

Value is:  .
Size  is: 3 .

When array moves out from function, he transforms from multidimensional into the monodimensional, and there is no my value in output. How i can avoid this bug?

Upvotes: 1

Views: 144

Answers (1)

guiwhatsthat
guiwhatsthat

Reputation: 2434

The return line in your code should look like that:

return (, $b)

This forces powershell to return your object at once. At default it returns each element separately.

Read more about it in the documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return?view=powershell-7 Search for Unary array expression

Upvotes: 1

Related Questions