Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading