PowerShell returns one element array from a function

Today I noticed an interesting PowerShell behavior, and I did the following code to show it. At startup:

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

You have:

 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'll get:

 System.Object[] System.Int32 

Can anyone provide more information about this "feature"? The PowerShell specification did not seem to mention this.

Thanks.


BTW, I checked the code on PowerShell versions 2, 3 and 4.

+6
source share
2 answers

Powershell automatically expands arrays in certain situations, in your case 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 the array into the assignment:

 $b = ,(test) 
+5
source

This tells you that this is an object, because technically it is.

 PS C:\Users\Administrator> $arr = @(1,2,3,4,5) PS C:\Users\Administrator> $arr.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array 

Note that BaseType is System.Array

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

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

Like this.

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

 PS C:\Users\Administrator> Write-Host $arr.GetType().BaseType System.Array 
-1
source

All Articles