Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell return a single element array from function

Today I noticed an interested behavior of PowerShell and I made the following code to show it. When you run:

function test()
{
    $a = @(1,2);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();

What you got is:

System.Object[]
System.Object[]

However when you change the code to:

function test()
{
    $a = @(1);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();

You will got:

System.Object[]
System.Int32

Can someone provide some more details on this "feature"? Seems the PowerShell specification did not mention this.

Thanks.


BTW, I tested the code on PowerShell version 2, 3 & 4.

like image 974
user133580 Avatar asked Jan 08 '14 10:01

user133580


1 Answers

Powershell automatically "unwraps" arrays in certain situations, in your case the assignment:

PS> (test).GetType()
System.Object[]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

PS> $b = test
System.Object[]
PS> $b.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can get around by explicitly introducing an array in the assignment:

$b = ,(test)
like image 72
Joey Avatar answered Nov 14 '22 03:11

Joey