Enumerating Disk Space on a Computer

Microsoft® Windows® 2000 Scripting Guide

You can use the Win32_LogicalDisk class to enumerate the available disk space on any computer in your organization.

Scripting Steps

Listing 10.6 contains a script that enumerates the free space on all the hard disk drives on a computer. To carry out this task, the script must perform the following steps:

  1. Create a constant named LOCAL_HARD_DISK and set the value to 3. This constant limits data retrieval to local hard disks (DriveType = 3).

  2. Create a variable to specify the computer name.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to "impersonate."

  4. Use the ExecQuery method to query the Win32_LogicalDisk class.

    Because free space is typically a concern only on local hard disks (as opposed to floppy disks or compact discs), a Where clause is included to limit data retrieval to local hard disks (DriveType = LOCAL_HARD_DISK). This results in a collection of all the hard disks installed on the computer.

  5. For each logical disk drive in the collection, echo the DeviceID and the value of the FreeSpace property.

Listing 10.6 Enumerating Free Disk Space

  
1
2
3
4
5
6
7
8
9
10
11
Const HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " _
 & HARD_DISK & "")
For Each objDisk in colDisks
 Wscript.Echo "Device ID: " & objDisk.DeviceID 
 Wscript.Echo "Free Disk Space: " & objDisk.FreeSpace
Next