PowerShell converts the values โ€‹โ€‹returned by the function. How to avoid this?

I am trying to return a List <T> from a PowerShell function, but get one of the following values:

  • null - for an empty list
  • System.Int32 - for a list with one element
  • System.Object [] - for a list with a large number of elements

the code:

function CreateClrList { $list = New-Object "System.Collections.Generic.List``1[System.Int32]" $list.Add(3) $list } Write-Host (CreateClrList).GetType() 
+4
powershell return-value
Mar 29 '09 at 21:59
source share
3 answers

Yes, powershell expands all collections. One solution is to return a collection containing the real collection using a unary comma:

 function CreateClrList { $list = New-Object "System.Collections.Generic.List``1[System.Int32]" $list.Add(3) ,$list } 
+9
Mar 29 '09 at 22:09
source share

Note that most of the time you want Powershell to expand the enumerated types so that the commands with the channels are executed faster and with earlier user feedback, since the commands down the channel can start processing the first elements and produce the result.

+1
Oct 20 '09 at 23:43
source share

If you need to return an int list, use the jachymko solution .

Otherwise, if you are not particularly interested in whether what you get is a list or an array, but just want to iterate the result, you can wrap the result in @ () when listing, for example.

 $fooList = CreateClrList foreach ($foo in @($fooList)) { ... } 

This will cause @($fooList) to have an array type โ€” an empty array, an array with one element or an array with several elements.

0
Oct 19 '12 at 7:07
source share



All Articles