Skip to main content

Explaining how a Division by Zero Error Occurs with Where-Object

While teaching PowerShell, I stress that when writing code  there are often multiple paths to success.  During one of our labs where we were learning how to utilize the Where-Object cmdlet, a member of my class pointed something out.  Let’s start by setting things up. 

The originating command being used is Get-Volume.  Here is what the results of Get-Volume look like without any filtering.

PS C:\> Get-Volume

DriveLetter FileSystemL FileSystem  DriveType   HealthStatu SizeRemaini       Size
            abel                                s                    ng          
----------- ----------- ----------  ---------   ----------- -----------       ----
            System R... NTFS        Fixed       Healthy        61.08 MB     350 MB
E           10961B A... NTFS        Fixed       Healthy        31.85 GB      32 GB
C                       NTFS        Fixed       Healthy        54.19 GB   63.66 GB
A                                   Removable   Healthy             0 B        0 B
D                                   CD-ROM      Healthy             0 B        0 B

Take notice that the A: and D: drives have zero bytes in both size and space remaining.  These are the sources of our issue.  The algorithm used utilizes division between both of these properties.  Here is the odd behavior.  The task was to get all drives where the size is greater than 0 and the drives have less than 99% free space.  Below is my answer:

PS C:\> Get-Volume |
    Where {$_.SizeRemaining -gt 0 -and $_.SizeRemaining / $_.Size -lt .99}

DriveLetter FileSystemL FileSystem  DriveType   HealthStatu SizeRemaini       Size
            abel                                s                    ng           
----------- ----------- ----------  ---------   ----------- -----------       ----
            System R... NTFS        Fixed       Healthy        61.08 MB     350 MB
C                       NTFS        Fixed       Healthy        54.19 GB   63.66 GB


Now here is his answer:

PS C:\> Get-Volume |
    Where {$_.SizeRemaining / $_.Size -lt .99 -and $_.SizeRemaining -gt 0}

DriveLetter FileSystemL FileSystem  DriveType   HealthStatu SizeRemaini       Size
            abel                                s                    ng          
----------- ----------- ----------  ---------   ----------- -----------       ----
            System R... NTFS        Fixed       Healthy        61.08 MB     350 MB
C                       NTFS        Fixed       Healthy        54.19 GB   63.66 GB
Where : Attempted to divide by zero.
At line:2 char:5
+     Where {$_.SizeRemaining / $_.Size -lt .99 -and $_.SizeRemaining -gt 0}
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Where-Object], RuntimeException
    + FullyQualifiedErrorId : RuntimeException,Microsoft.PowerShell.Commands.Wher
   eObjectCommand
 

Look carefully.  The only difference is on the left and right of the –and operator.  The two comparisons are the same, just presented in a different order. 

Get-Volume |
    Where {$_.SizeRemaining -gt 0 -and $_.SizeRemaining / $_.Size -lt .99}

Get-Volume |
    Where {$_.SizeRemaining / $_.Size -lt .99 -and $_.SizeRemaining -gt 0}

To resolve this, I looked at the help file for About_Logical_Operators.  Below is the paragraph that solves this mystery:

    The Windows PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the and operator is FALSE, the right operand is not evaluated. If the left operand in a statement that contains the or statement is TRUE, the right operand is not evaluated. As a result, you can use these statements in the same way that you would use the If statement.

So in my answer, I filtered out the A: and D: drives because they did not pass the first test where their size must be greater than zero.  Since the –and operator is used and the left equated to FALSE, the second comparison is never executed thereby not generating the division by zero error. In the other solution, the division is performed before the test to make sure the drive has more than 0 bytes remaining.  This causes division by zero.

I can understand this behavior from the perspective of efficiency.  For the –and operation to work, both sides need to equate to TRUE.  Since the left hand operation is FALSE, there is no reason to waste CPU time on the right hand operation.  The logical operator –and absolutely will not be TRUE if the first comparison fails.


Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.