Wednesday, March 12, 2008

Powershell method for testing for NULL

I guess this is obvious, but I was looking for means of evaluating whether or not a variable was null by trying:
If ($Varable -eq NUL) {some action}
Which of course caused an error. VBScript has the IsNull(value) function, but there I could find no results googling for a similar one in PowerShell.

It turns out, this is much simpler than I was making it out to be:

To see if a variable is null, simply check:
If (!$Variable) {some action}
Conversely, to verify if the variable has any value:
If ($Variable) {some action}

*sigh* sometimes the simple answers take the longest to find ;-)

8 comments:

Anonymous said...

oh, thanks! This is bizarrely difficult to find - I guess everyone just assumes it's obvious :)

Anonymous said...

You almost had it!

This works as well:

If ($Variable -eq $null) {some action}

note the $null .... not easy to guess but it works, there is also $true, $false in the same idea

Anonymous said...

Very helpful, thank you

Chris Monahan said...

And another thank you. The blog post that keeps on giving. As a Powershell newbie it's nice to be able to find these answers in less than a minute with an Internet search.

Anonymous said...

Thanks !

I was looking for the same thing ;)

SMC said...

Same here.

Anton said...

Be careful, this condition is true also when the value of $Variable is the number 0. Use the $null check instead.

Anonymous said...

Exactly what I was looking for. You just saved me a lot of frustration.

You'd think I would have thought of that, though, since that's how you test for null in Perl and PHP and PowerShell is fairly similar to both of those.