Testing a variable with the value of zero

Testing a variable with the value of zero

  •  
  •  
  •  
  •  
  •  
  •  
  •  
Rate this post

Tonight, while working on my previous script, I ran into an interesting problem when testing the presence of a value.

Consider this:

PS C:\> [int]$IntValue0 = 0
PS C:\> [int]$IntValue1 = 1
PS C:\> [string]$StringValue0 = "0"
PS C:\> [string]$StringValue1 = "1"
PS C:\> $IntValue0
0
PS C:\> $IntValue1
1
PS C:\> If ($IntValue0) { "exists" }
PS C:\> If ($IntValue1) { "exists" }
exists
PS C:\> if ($StringValue0) { "exists" }
exists
PS C:\> if ($StringValue1) { "exists" }
exists
PS C:\> if ($IntValue0 -eq $null) { "null" }
PS C:\> if ($IntValue0 -lt 1) {"less than 1" }
less than 1
PS C:\> $IntValue0.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType

My short lesson: when setting an integer value to 0, you can’t test for it using If ($Value), as that will return false.  If you want to test for the presence of a value AND determine that it’s greater than 0, it would seem that you have to use If ($Value -lt 1) { “do this if less than 1” }.

Let’s do a story problem.

You have 4 oatmeal raisin cookies.  Alice wants 3 cookies, James wants 2 cookies, and Mickey wants 0 cookies (since they contain that dreaded fool’s chocolate).

$Alice = 3
$James = 2
$Mickey = 0

You can then attempt to test for the presence of $Alice, $James, or $Mickey in a simple If statement, and then see the problem if you’re attempting to do something based on the integer value.  It works as expected until you get to Mickey:

You can see why we got the result we did:

You can still do arithmetic with $Mickey, since it’s an integer:

So, while it’s technically not null, when testing for its presence using the If ($value) construct, a variable set to “0” will return a boolean False (since 0 is false and 1 is true).  You can, however, test for a variable with a value of 0 a few ways that I’ve discovered:

If ($Value -ne $null) – Again, having a value of 0 is different than $null, so this will return True (I think this is probably the best?)

If ($Value -lt 1) – The numerical value of 0 is less than 1, so this will return True

If ($Value.Length -ge 1) – You can use the length of the variable (a length greater than or equal to 1) to test for its presence

If ([string]$Value) – You can test $Value as a string (the text value is 0), and this will also return True

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.