VBScript: Drive Utilization

Here’s another recent topic from the ScriptingAnswers.com forums which I thought I’d share. The forum members wanted to delete files if the drive utilization exceeded a certain threshold. Using Windows Management Instrumentation (WMI) with VBScript I came up with something like this:

   1: Function Utilization (strComputer,strDrive)
   2:  
   3:     Set objWMIService = GetObject("winmgmts://" & strComputer)
   4:     strQuery="Select * from win32_logicaldisk where DeviceID='" & strDrive & "'"
   5:     Set colWMI=objWMIService.ExecQuery(strQuery)
   6:     For Each item In colWMI
   7:         u=(item.size-item.freespace)/item.size
   8:     Next
   9:     
  10:     Utilization=u
  11:  
  12: End Function
  13:  
  14: 'sample usage
  15: strDrive="G:"
  16: strComputer="localhost"
  17: iUsed=Utilization(strComputer,strDrive)
  18:  
  19: 'display a warning if percent used is greater than 75%
  20: If iUsed > .75 Then
  21:     WScript.Echo "WARNING: Drive " & strDrive & " on " &_
  22:      strComputer & " is at " & FormatPercent(iUsed) & " utilization"
  23: Else
  24:     WScript.Echo "OK: Drive " & strDrive & " on " &_
  25:      strComputer & " is at " & FormatPercent(iUsed) & " utilization"
  26: End If

This script is slightly different than what I originally posted but I think it offers greater flexibility. The function itself takes a computername and drive as parameters. The drive must be specified with the colon, like G: or C:. Using WMI I query the computer for the drive information using the Win32_logicaldisk (line 3). As I enumerate the returned object, I calculate the drive utilization by subtracting the freespace value from the size value and dividing the result by the disk size (line 7). The returned value will be less than 1 which is what perfectly fine once you see how I’m going to use it.

In the sample usage section you can see that I’m getting the utilization value for drive G: on the local host (line 17). One line 20 I have an If statement that compares the returned value. If the value is greater than .75 (75%) then I’ll display a warning message. To make it pretty, I can use the FormatPercent function with iUsed so that the warning message looks like this:

WARNING: Drive G: on localhost is at 79.87% utilization

I’m sure there are other ways you can think of to use this function. Enjoy.

Download the VBS file here