Enumerating a Specific Set of Files

Microsoft® Windows® 2000 Scripting Guide

One of the advantages of using WMI as a file management tool is the fact that WMI allows you to locate all the files that meet a specified set of criteria, regardless of the physical location of those files. For example, you can return a collection of all the files consisting of a particular file name extension, all the read-only files, or all the files created on a specified date. After these files are enumerated, you can carry out various operations on the entire collection, including copying, deleting, or renaming each of the files.

Tip

  • If you want to limit your search to a particular drive, include the appropriate Where clause in your query. For example, the clause Where Drive = "C" limits the search to files found on drive C.

Scripting Steps

Listing 11.22 contains a script that returns a set of all the files with a file size larger than 1,000,000 bytes. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

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

  3. Use the ExecQuery method to query the CIM_Datafile class.

    To limit data retrieval to a specific set of files, a Where clause is included restricting the returned files to those with a size of 1,000,000 bytes or more.

  4. For each file in the collection, echo the file name and the file size.

Listing 11.22 Enumerating a Specific Set of Files

  
1
2
3
4
5
6
7
8
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
 ("SELECT * FROM CIM_DataFile WHERE FileSize > 1000000")
For Each objFile in colFiles
 Wscript.Echo objFile.Name & " - " & objFile.FileSize
Next