0

The following code

$a = 1..5 | % {
    $l = $_, ($_+1), ($_+2)
    $r = $_ * 100
    $l, $r
    #$l.Add($r) # Error
}
$a | % { "[$_]" }

returns

[1 2 3]
[100]
[2 3 4]
[200]
[3 4 5]
[300]
[4 5 6]
[400]
[5 6 7]
[500]

However, I expected the following result?

[1 2 3 100]
[2 3 4 200]
[3 4 5 300]
[4 5 6 400]
[5 6 7 500]
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • Related: http://stackoverflow.com/questions/11107428/how-can-i-force-powershell-to-return-an-array-when-a-call-only-returns-one-objec and http://stackoverflow.com/questions/14085077/powershell-how-can-i-to-force-to-get-a-result-as-an-array-instead-of-object?lq=1 – Eris Sep 17 '15 at 21:57

2 Answers2

1

, does not append but creates a new array consisting of two items.

Use + to append an item, and then prefix it with , to escape flattening of the array by the pipeline:

$a = 1..5 | % {
    $l = $_, ($_+1), ($_+2)
    $r = $_ * 100
    ,($l + $r)
}
$a | % { "[$_]" }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

I figured out a way but don't know why it works.

$a = 1..5 | % {
    $l = $_, ($_+1), ($_+2)
    $r = $_ * 100
    #$($l, $r)
    $l += $r
    ,@($l)
}
$a | % { "[$_]" }
ca9163d9
  • 27,283
  • 64
  • 210
  • 413