How to test for $null array in PowerShell

184,550

Solution 1

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

Solution 2

You can reorder the operands:

$null -eq $foo

Note that -eq in PowerShell is not an equivalence relation.

Solution 3

if($foo -eq $null) { "yes" } else { "no" }

help about_comparison_operators 

displays help and includes this text:

All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.

Solution 4

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

Solution 5

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.

Share:
184,550
Mark Berry
Author by

Mark Berry

Updated on July 08, 2022

Comments

  • Mark Berry
    Mark Berry almost 2 years

    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 = $null
    PS C:\> $foo -eq $null
    True
    

    But when I give it a value, the test for $null does not return anything:

    PS C:\> [array]$foo = @("bar")
    PS C:\> $foo -eq $null
    PS C:\>
    

    How can "-eq $null" give no results? It's either $null or it's not.

    What is the correct way to determine if an array is populated vs. $null?