Login   /   Register

Determine if a Folder Has Any Files with a Specific File Extension

Rate this article
     0 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 5
Loading ... Loading ...
March 31st, 2008 by daniva

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 .bak files found in the C:\Logs folder:

Option Explicit
 
Dim wmiService, files
Set wmiService = GetObject( "winmgmts:\\.\root\cimv2" )
Set files = wmiService.ExecQuery( _
    "SELECT * FROM CIM_DataFile WHERE Path = '\\Logs\\’ " & _
    "AND Drive = 'C:’ AND Extension = 'bak’" )
 
Print "Number of .bak files found: " & files.Count

If you look closely at this script you might notice a couple things. First, we didn’t specify the path as C:\Logs; instead, we separated the drive (C:) from the folder (Logs). 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 divided 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:\Logs. 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 Logs. That would include D:\Logs (and E:\Logs and F:\Logs and …) as well as C:\Logs.

Second, you might note that we used double \\’s to surround the Path; thus we have \\Logs\\ rather than \Logs\ (i.e., C:\Logs ). 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.

 

Based on "How Can I Tell if a Folder Has Any Files with a Specific File Extension?" from the Scripting Guys.

Posted in WMI

Leave a Reply

You must be logged in to post a comment.

This article was viewed 432 times