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.


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)

It's telling you that it is an object, because technically it is.

PS C:UsersAdministrator> $arr = @(1,2,3,4,5)
PS C:UsersAdministrator> $arr.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Note that the BaseType is System.Array

But when you output it using Write-Host , it just tells you that it is a System.Object[]

PS C:UsersAdministrator> Write-Host $arr.GetType()
System.Object[]

Like that.

So it makes logical sense that we can run the following command, based on the table above, to find out the BaseType :

PS C:UsersAdministrator> Write-Host $arr.GetType().BaseType
System.Array
链接地址: http://www.djcxy.com/p/18288.html

上一篇: Prestashop定制/计算产品价格

下一篇: PowerShell从函数返回一个单元素数组