Wednesday, June 30, 2010

Testing NULL values with Powershell

When a developer has to do an IT pro job, he does what he knows best: writing code. So I started with writing some powershell scripts to automate some administrator jobs.

One thing you may not forget is that Powershell is a lot more friendly for NULL values than C#, so don’t forget to check your objects for NULL values. In Powershell this is very clean and easy to do.

To see if a variable is null, simply check:

   1:  If (!$Variable) {some action}
Conversely, to verify if the variable has any value:
   1:  If ($Variable) {some action}


Anonymous said...

What about :
$a=$null; if ($a) {"has VALUE"} else {"is NULL"}


$a=0; if ($a) {"has VALUE"} else {"is NULL"}


$a=1; if ($a) {"has VALUE"} else {"is NULL"}

Conrad Braam said...

Yeah, fails in the case of $a=0.