0

The bellow example

Function Get-ListOfList
{

$listOfLists =  New-Object System.Collections.ArrayList
$List =  New-Object System.Collections.ArrayList

$List.Add("A") | Out-Null
$List.Add("B") | Out-Null

$listOfLists.Add($List) | Out-Null  
return $listOfLists

}

I would expect this to return a single list , with 1 item in it , a list. That list has 2 strings in it.

But what is happening is that it returns a list , with 2 items in it.

  $l =  Get-ListOfList
  $l.Count
  $l.GetType().Name
  $l[0].Count
  $l[0].GetType().Name
  $l[1].Count
  $l[1].GetType().Name

outputs

2
ArrayList
1
String
1
String

This is messing things up as the behavior is different when the list of list has more then 1 item in it , it returns what you expect.

deetle
  • 197
  • 8
  • 3
    Yes this is expected, powershell is enumerating your output. use `, $listOfLists` – Santiago Squarzon Jun 15 '22 at 14:03
  • PowerShell [Gotcha `#4` the pipeline unrolls](https://stackoverflow.com/a/69644807/1701026) – iRon Jun 15 '22 at 14:16
  • So you are saying in PowerShell I can not expect to get back what is being returned , but I need an if statement , if I get a list of lists process it one way , and if I get a list of string process it another way. Really ? – deetle Jun 15 '22 at 14:32
  • No, if you want to force an array output from within your function, you might use the [unary comma `,`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#comma-operator-), see @Santiago's note, and if you want force an array at the outside of the function, you might use the [array subexpression operator `@( )`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#array-subexpression-operator--), e.g.: `$l = @(Get-ListOfList)` – iRon Jun 15 '22 at 15:19
  • Return the list of lists as 'return ,$ListOfList' with the comma prefix solves the problem. Thanks – deetle Jun 17 '22 at 16:48

0 Answers0