Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
Mark Berry Avatar asked Feb 24 '11 22:02

Mark Berry


People also ask

How do I use $null in PowerShell?

$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.

How do you check if an array has a null value?

To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null .

How do you check if an object is empty in PowerShell?

Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System. Object] will be true for any possible non-null value.


1 Answers

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

like image 197
Taylor Bird Avatar answered Oct 19 '22 05:10

Taylor Bird