PowerShell converts values returned from function. How to avoid this?

前端 未结 4 1331
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 06:59

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

  1. null - for empty list
  2. System.Int32 - for list with one element
  3. Sy
相关标签:
4条回答
  • 2021-01-13 07:10

    If you need to return a list of ints, use jachymko's solution.

    Otherwise, if you do not particularly care whether what you get is a list or array, but just want to iterate through result, you can wrap result in @() while enumerating, e.g.

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

    That would cause @($fooList) to be of array type - either an empty array, array with one element or array with multiple elements.

    0 讨论(0)
  • 2021-01-13 07:12

    Note that most of the time, you want Powershell to unroll enumerable types so that piped commands execute faster and with earlier user feedback, since commands down the pipe can start processing the first items and give output.

    0 讨论(0)
  • 2021-01-13 07:24

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

    function CreateClrList
    {
        $list = New-Object "System.Collections.Generic.List``1[System.Int32]"
        $list.Add(3)
        ,$list
    }
    
    0 讨论(0)
  • 2021-01-13 07:26

    PowerShell 5.0 added support for classes and hence methods where the return type can be specified. To control the type returned, use a class with a static method:

    class ListManager {
        static [System.Collections.Generic.List[int]] Create() {
            [System.Collections.Generic.List[int]] $list =
                [System.Collections.Generic.List[int]]::new()
    
            $list.Add(3)
    
            return $list
         }
    }
    
    [ListManager]::Create().GetType()
    
    0 讨论(0)
提交回复
热议问题