Enumerating Objects of a Particular Class

Now let's enumerate all l ogical disks on a machine. To do so, we need to use the InstancesOf method. An example should make this clear:

strComputer = "."
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set objDisks = objWMI.InstancesOf("Win32_LogicalDisk")
for each objDisk in objDisks
    Wscript.Echo "DeviceID: " &  objDisk.DeviceID    
    Wscript.Echo "FileSystem: " &  objDisk.FileSystem    
    Wscript.Echo "FreeSpace: " & objDisk.FreeSpace    
    Wscript.Echo "Name: " & objDisk.Name    
    Wscript.Echo "Size: " & objDisk.Size    
    WScript.Echo ""

Here we get a WMI object which points to the root\CIMv2 namespace, after which we call the InstancesOf method and pass the Win32_LogicalDisk class. That method returns a collection of Win32_LogicalDisk objects, which we then iterate over with a for loop.

Since we used a for loop in the last example, we'll show the equivalent code in Perl:

use Win32::OLE 'in';
my $strComputer = ".";
my $objWMI = Win32::OLE->GetObject("winmgmts:\\\\$strComputer\\root\\cimv2");
my $objDisks = $objWMI->InstancesOf("Win32_LogicalDisk");
for my $objDisk (in $objDisks) {
    print "DeviceID: ", $objDisk->DeviceID,"\n";
    print "FileSystem: ", $objDisk->FileSystem    ,"\n";
    print "FreeSpace: ", $objDisk->FreeSpace,"\n";
    print "Name: ", $objDisk->Name,"\n";    
    print "Size: ", $objDisk->Size,"\n";
    print "\n";

As you can see, the Perl code is very similar to the VBScript code. One thing to note is that we had to import the in function on the first ...

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.