How to handle $null in the pipeline

后端 未结 4 1008
北恋
北恋 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 08:09

    If you can modify your function, have it return an empty collection/array instead of $null:

    PS> function Empty { $null }
    PS> Empty | %{'hi'}
    hi
    
    PS> function Empty { @() }
    PS> Empty | %{'hi'}
    

    Otherwise, go with what Oisin suggests although I would suggest a slight tweak:

    filter Skip-Null { $_|?{ $_ -ne $null } } 
    

    Otherwise this will also filter 0 and $false.

    Update 4-30-2012: This issue is fixed in PowerShell v3. V3 will not iterate over a scalar $null value.

提交回复
热议问题