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

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.

How to run GPResult on a remote client with PowerShell

In the past, to run the GPResult command, you would need to either physically visit this client, have the user do it, or use and RDP connection.  In all cases, this will disrupt the user.  First, you need PowerShell remoting enabled on the target machine.  You can do this via Group Policy . Open PowerShell and type this command. Invoke-Command –ScriptBlock {GPResult /r} –ComputerName <ComputerName> Replace <ComputerName> with the name of the target.  Remember, the target needs to be online and accessible to you.

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below. The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings. Create action This give you a green triangle. The Create action creates a new mapped drive for users. Replace Action The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping. Update Action The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the ma...