noobservergirl
noobservergirl

Reputation: 21

Calculating percentage: Attempted to divide by zero error

I can't work out why the script is calculating the disk freespace storage correctly but issues the "Attempted to divide by zero" error on execution. Can anyone shed light on this? I know that there are other more efficient ways to get the percentage but I'm determined to crack this one!

Get-WmiObject Win32_LogicalDisk -ComputerName "*servername*" |
ForEach-Object {
'Disk {0} has {1:0.0} GB space available out of {2:0.0} GB   {3:p0} Freespace' -f $_.Caption, ($_.FreeSpace / 1GB), ($_.Size / 1GB), ($_.Freespace / $_.Size)
}

Disk C: has 30.9 GB space available out of 79.7 GB 39%

Disk E: has 18.8 GB space available out of 20.0 GB 94%

Disk L: has 332.2 GB space available out of 377.0 GB 88%

Attempted to divide by zero.

At line:3 char:1

'Disk {0} has {1:0.0} GB space available out of {2:0.0} GB {3:p0} '

CategoryInfo : NotSpecified: (:) [], RuntimeException FullyQualifiedErrorId : RuntimeException

Upvotes: 2

Views: 1605

Answers (1)

codewario
codewario

Reputation: 21468

One of your disks has a Size of 0. This is (to my knowledge) only possible in one of three scenarios:

  1. Your partition table is corrupted
  2. Your disk is visible but is failing
  3. Removable storage that doesn't have any storage (e.g. SD card reader with no card inserted)

If the issue is one of the former two, you can attempt to fix partition or disk issues with chkdisk, diskpart or PowerShell's Storage Module, but back the data up first since it's very easy to nuke data with these tools. To get your script working as intended in any of the scenarios, read on.

In your code you can attempt to detect this with an if statement and act accordingly:

Get-WmiObject Win32_LogicalDisk -ComputerName "*servername*" | ForEach-Object {
  if( $_.Size -ne 0 ) {
    'Disk {0} has {1:0.0} GB space available out of {2:0.0} GB   {3:p0} Freespace' -f $_.Caption, ($_.FreeSpace / 1GB), ($_.Size / 1GB), ($_.Freespace / $_.Size)
  } else {
    # Disk is 0 bytes case
  }
}

Another approach you could take is to filter out any disks with a size of 0 using Where-Object:

Get-WmiObject Win32_LogicalDisk -ComputerName "*servername*" | Where-Object {
  $_.Size -ne 0
} | Foreach-Object {
'Disk {0} has {1:0.0} GB space available out of {2:0.0} GB   {3:p0} Freespace' -f $_.Caption, ($_.FreeSpace / 1GB), ($_.Size / 1GB), ($_.Freespace / $_.Size)
}

Upvotes: 1

Related Questions