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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With