3

I'm trying to understand array unrolling in Posh and the following puzzles me. In this example I return the array wrapped in another array (using a comma), which basically gives me the original array after the outer array gets unrolled on return. Why then do I get a correct result (just the array) when I indirectly wrap the result by using the array operator (@) on a variable with the result, but get an array in an array if I use @ directly on the function? Does @ operator behave differently for different types of its parameter? Is there any PS help article for the @ operator and the array unrolling?

function Unroll
{
    return ,@(1,2,3)
}

Write-Host "No wrapper"
$noWrapper = Unroll #This is array[3]
$noWrapper | % { $_.GetType() }

Write-Host "`nWrapped separately"
$arrayWrapper = @($noWrapper) #No change, still array[3]
$arrayWrapper | % { $_.GetType() }

Write-Host "`nWrapped directly"
$directArrayWrapper = @(Unroll) #Why is this array[1][3] then?
$directArrayWrapper | % { $_.GetType() }
Write-Host "`nThe original array in elem 0"
$directArrayWrapper[0] | % { $_.GetType() }

Thanks

PScripter
  • 31
  • 2

2 Answers2

0

If you remove the comma operator from the Unroll function, it behaves at you should expect.

function Unroll
{
    return @(1,2,3)
} 

In this case $arrayWrapper = @($noWrapper) is the same as $directArrayWrapper = @(Unroll).

You may find more information about array unrolling with this SO question and in this article about array literals In PowerShell

Community
  • 1
  • 1
Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74
  • 1
    This is of course true, but you don't always have access to the original code, or cannot change it, as it's e.g. a library. The question was more about why this thing happens and how to have a consistent way of handling it regardless of how exactly the array is returned to you. – PScripter Jun 25 '12 at 22:42
0

Looking at this other question, it seems that

Putting the results (an array) within a grouping expression (or subexpression e.g. $()) makes it eligible again for unrolling.

which seems to be what happen here.

Community
  • 1
  • 1
Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74