Should PowerShell return object [] from the pipe?

Given this function:

> function Get-ArrayOfArrays() {
    (1,2),(3,4) | % { $_ }
}

I would expect the return type to be an array of arrays. However, it seems that the internal arrays are expanding into the pipe:

> Get-ArrayOfArrays | % { $_.GetType().Name }
Int32
Int32
Int32
Int32

In fact, running inline will produce the following results:

> (1,2),(3,4) | % { $_ }
Object[]
Object[]

I found that if I use the return keyword inside foreach, I can achieve the desired result:

> function Get-ArrayOfArraysWithReturn() {
    (1,2),(3,4) | % { return $_ }
}

> Get-ArrayOfArraysWithReturn | % { $_.GetType().Name }
Object[]
Object[]

This behavior is similar to "If returned from a function with uncaught objects, and these objects become arrays and then expand them." Is this one of those do-what-good-time solutions? Or am I missing something else?

+3
source share
2 answers
(1,2),(3,4) | % {$_}

leads to the conclusion of your function (1,2) and (3,4) - the same as this function:

function foo { 
    1,2
    3,4 
}

, , () , , :

PS> foo | %{$_.GetType().Name}
Int32
Int32
Int32
Int32

, :

PS> 1,2
1
2

, . , :

function Get-ArrayOfArrays() { 
    (1,2),(3,4)
}

(1,2), (3,4) , , (1,2) (3,4). , , - , ,, , :

PS> function foo { ,((1,2),(3,4)) }
PS> foo | gtn
Object[]
+4

, : " PowerShell // ?".

, , , :

> (1, 2), (3, 4)
1
2
3
4

, :

[ 1, 2 ] ++ [ 3, 4 ] == [ 1, 2, 3, 4 ] 

.

,

1, 2, 3 | ForEach-Object { $_, ($_ * 2) }

[ x, x * 2 ] . :

[ 1, 2, 2, 4, 3, 6 ]

:

[ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]

,, :

$list = 1, 2, 3 | ForEach-Object { , ($_, ($_ * 2)) }

, int :

1   -> [ [ 1, 2 ] ]
2   -> [ [ 2, 4 ] ]    
3   -> [ [ 3, 6 ] ] 

, , $list :

[ [ 1, 2 ] ] + [ [ 2, 4 ] ] + [ [ 3, 6 ] ] == [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]

,

> $list[0]   #  get first element of list, should be [ 1, 2 ]
1
2
> $list[2][1]  # from the third elem, [ 3, 6 ], get 2nd elem, should be 6
6

, , :

[ 1, 2 ] ++ [ 2, 4 ] ++ [ 3, 6 ] == [ 1, 2, 2, 4, 3, 6 ]

> $list
# prints [ 1, 2, 2, 4, 3, 6 ]
0

Source: https://habr.com/ru/post/1736179/


All Articles