The Kirkland Coder: PowerShell IsEmptyOrNull?

Thursday, February 23, 2012

PowerShell IsEmptyOrNull?

The current version of PowerShell allows for a quick and easy way to check if a variable is NULL or EMPTY. Just place the variable as the condition of an "IF" statment. Here is an example with an array:

# Set $a as an EMPTY array
$a = @()

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

# Set $a as a NULL
$a = $null

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

The output is:

NULL or EMPTY
NULL or EMPTY

There you have it. I tend to use beacuse it looks clean, but as I like to say, "Programming is an Art, and there are a lot of crappy painters out there".

No comments:

Post a Comment