Extreme file and folder scripting: Listing a directory tree recursively - Day 3 – Bonus script: Using WMI with LIKE

 

When I showed these scripts to Dean, he thought there had to be an easier way to recurse through a directory tree with WMI, and he found it.  The only caveat is that you must run it on Windows XP or Windows Server 2003.  This is because WMI Query Language, the SQL dialect that you use with the ExecQuery method of SwbemServices, first added the LIKE keyword in Windows XP (see https://msdn.microsoft.com/library/en-us/wmisdk/wmi/like_operator.asp).

 

In this case, LIKE enables you to query for all directories that contain a specific string, surrounded by percent signs, for example: "%c:\\ff%" (remember that WQL queries require two backslashes rather than one to delimit file paths).  This would include all subdirectories of c:\ff and their subdirectories.  In other words, LIKE enables you to use WQL's equivalent of wildcards.  You can also use the percent sign at just one side of the string.  In this script we use "c:\\ff%", which returns any path on c: drive that begins with "ff".  Keep in mind that this will also return not just the subdirectories of c:\ff, but also any other top level folders that begin with ff, such as c:\ffx.

 

The query including LIKE in this script seems to run very slowly, at least on my computer.  That may be because my computer is old and cantankerous, like me.  Or it may be because WMI has to search the whole file system to make sure there are no other matches that are LIKE the string.

 

Here's Dean's script, which I suppose we could call Files-list-recurse-like-wmi.vbs, except that the name is getting too long.  Call it what you will.

 

strComputer = "."

strFolderRoot = "c:\\ff"

Set objWMIService = GetObject("winmgmts:" _

 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colFolders = objWMIService.ExecQuery _

 ("Select * from Win32_Directory where Name Like '" & strFolderRoot & "%'")

For Each objFolder in colFolders

  Wscript.Echo "Folder: " & objFolder.Name

  strTMP = Replace(Mid(objFolder.Name,4,Len(objFolder.Name)),"\","\\")

  strQuery = "SELECT * FROM CIM_DataFile WHERE Drive = 'c:' " & _

   "AND Path = '\\" & strTMP & "\\'"

  Set colFiles = objWMIService.ExecQuery(strQuery)

  On Error Resume Next

  For Each objFile in colFiles

    WScript.Echo "File: " & objFile.Name

  Next

Next

Comments

  • Anonymous
    August 14, 2004
    Extreme file and folder scripting: Listing a directory tree recursively - Day 3 – Bonus script: Using WMI with LIKE
  • Anonymous
    November 25, 2007
    PingBack from http://feeds.maxblog.eu/item_1015989.html