How to test for $null array in PowerShell

前端 未结 6 988
感情败类
感情败类 2020-12-08 00:24

I\'m using an array variable in PowerShell 2.0. If it does not have a value, it will be $null, which I can test for successfully:

PS C:\\> [array]$foo =          


        
6条回答
  •  青春惊慌失措
    2020-12-08 00:58

    How do you want things to behave?

    If you want arrays with no elements to be treated the same as unassigned arrays, use:

    [array]$foo = @() #example where we'd want TRUE to be returned
    @($foo).Count -eq 0
    

    If you want a blank array to be seen as having a value (albeit an empty one), use:

    [array]$foo = @() #example where we'd want FALSE to be returned
    $foo.PSObject -eq $null
    

    If you want an array which is populated with only null values to be treated as null:

    [array]$foo = $null,$null
    @($foo | ?{$_.PSObject}).Count -eq 0 
    

    NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

提交回复
热议问题