How to handle $null in the pipeline

后端 未结 4 1004
北恋
北恋 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:45

    I don't think anyone likes the fact that both "foreach ($a in $null) {}" and "$null | foreach-object{}" iterate once. Unfortunately there is no other way to do it than the ways you have demonstrated. You could be pithier:

    $null | ?{$_} | % { ... }
    

    the ?{$_} is shorthand for where-object {$_ -ne $null} as $null evaluated as a boolean expression will be treated as $false

    I have a filter defined in my profile like this:

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

    Usage:

    $null | skip-null | foreach { ... }
    

    A filter is the same as a function except the default block is process {} not end {}.

    UPDATE: As of PowerShell 3.0, $null is no longer iterable as a collection. Yay!

    -Oisin

提交回复
热议问题