Search code examples
powershellnull

How to test for $null array in PowerShell


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?


Solution

  • 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