How to handle $null in the pipeline

后端 未结 4 1005
北恋
北恋 2021-02-05 07:25

I often have the following situation in my PowerShell code: I have a function or property that returns a collection of objects, or $null. If you push the results in

4条回答
  •  孤街浪徒
    2021-02-05 07:55

    A quick note to Keith's answer to complete it

    Personally, I would return nothing. It makes sense:

    PS> function Empty { if ('a' -eq 'b') { 'equal' } }
    PS> Empty | % { write-host result is $_ }
    

    But now you are in problems if you assign result from Empty to a variable:

    PS> $v = Empty
    PS> $v | % { write-host result is $_ }
    

    There is a little trick to make it work. Just wrap the result from Empty as a array like this:

    PS> $v = @(Empty)
    PS> $v | % { write-host result is $_ }
    PS> $v.GetType()
    IsPublic IsSerial Name      BaseType
    -------- -------- ----      --------
    True     True     Object[]  System.Array
    PS> $v.Length
    0
    

提交回复
热议问题