Hey, Scripting Guy! How can I verify whether or not any files with a specific file extension exist in a folder?
Hey, GM. This is actually a pretty easy thing to do. All we have to do is write a WMI query that includes the path of the folder we want to check as well as the file extension we’re checking for. For example, this script retrieves a collection of all the .txt files found in the C:\Scripts folder:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
ExecQuery("SELECT * FROM CIM_DataFile WHERE Path = '\\Scripts\\' " & _
"AND Drive = 'C:' AND Extension = 'txt'")
Wscript.Echo "Number of .txt files found: " & colFiles.Count
If you look closely at this script (and you guys do look closely at all this stuff, don’t you?) you might notice a couple things. First, we didn’t specify the path as C:\Scripts; instead, we separated the drive (C:) from the folder (Scripts). Why did we do that? Well, because - for better or worse - that’s how the CIM_DataFile class works; what we think of as the file path is divvied up between the drive and the folders. The Drive parameter is actually optional here; we could leave it out unless we also have a folder named D:\Scripts. If that was the case, then the Drive parameter becomes mandatory; leave it out, and the query returns all the files found in a folder with the path Scripts. That would include D:\Scripts (and E:\Scripts and F:\Scripts and …) as well as C:\Scripts.
Second, you might note that we used double \\’s to surround the Path; thus we have \\Scripts\\ rather than \Scripts\ (i.e., C:\Scripts). Why? Again, that’s just the way WMI works; any time you include a file path in a WHERE clause you need to use two \\’s. What if we wanted to check the folder C:\Documents and Settings\Ken Myer\Desktop\Work Files to see if it had any .txt files in it? In that case, our WHERE clause would look like this:
WHERE Path = '\\Documents and Settings\\Ken Myer\\Desktop\\Work Files\\
Note, too the two \\’s at the end of the Path. Those are important; don’t leave them out. (Well, unless you don’t care whether or not the script actually works.) And as long as we’re busy noting things, note that we don’t include the period when specifying the file extension; it’s just txt, not .txt.
After we get our collection back, all we have to do is echo the value of the collection’s Count property. This will tell us how many .txt files were found. If the Count is 0, we didn’t find any; if the Count is 7, we found 7. If - well, you can figure out the rest yourself.
See, we told you this was easy. Hey, every once in a while, we actually do know what we’re talking about!