Find out if variable is null or an array containing null variables in PowerShell

I am trying to find out if a variable is null or is an array containing null variables.

So for example, a short expression that will match ‘false’ for each of the following, but ‘true’ for anything else:

$nullvariable = $null
$nullvariable1 = @($null)
$nullvariable2 = @($null, $null)
$nullvariable3 = @("1", $null)

Context: I have some Compare-Object calls where I am trying to avoid ‘Cannot bind argument to parameter ‘ReferenceObject’ because it is null’ errors. The first answer here: https://stackoverflow.com/a/45634900/12872270 works but it’s not very legible/comprehensible code.

The remaining answers use an ‘if’ statement which is more legible, but in my testing Compare-Object doesn’t just fail for $null, but also any array containing null entries – the given examples using ‘if’ don’t account for that.

Detecting an array containing null variables seems like a separate problem in its own right anyway, hence the question.

>Solution :

Since containment operators can evaluate against scalars as well as collections, in this case you can either use -contains or -in with any of your variables and the result would be $true:

$null -in $nullvariable         # True
$nullvariable1 -contains $null  # True
$null -in $nullvariable2        # True
$nullvariable3 -contains $null  # True

Leave a Reply