Hey, Scripting Guy! Question

Hey, Scripting Guy! Is it possible to search a computer for .MP3 files or other files my users aren’t supposed to have?

-- AK

SpacerHey, Scripting Guy! AnswerScript Center

Hey, AK. Once again it’s WMI to the rescue. Using the CIM_DataFile class it’s easy to search a computer for specific file types. Want to know if your users have any .MP3 files lying around? Then just use a script similar to this:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile where Extension = 'mp3'")
For Each objFile in colFiles
    Wscript.Echo objFile.Name 
Next

As you can see, this is a pretty standard WMI script: we’re just looking for all instances of the CIM_DataFile class that have an Extension of MP3 (note that you don’t include the period; it’s MP3 and not .MP3). A very simple little script, and it runs reasonably fast: on a 2.39 GHz laptop, with 512 MB of RAM and 30 gigabytes of hard disk space, we got back a list of all the .MP3 files in less than 30 seconds.

It’s even possible to search for more than one file type with a single query. For example, this script searches for .WMA files as well as .MP3 files:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile where Extension = 'mp3' OR Extension = 'wma'")
For Each objFile in colFiles
    Wscript.Echo objFile.Name 
Next

But that’s not the cool thing. You said these are files your users are not allowed to have; we’re guessing that means you’d like them removed from their computers. The preceding script won’t do that; it just reports back the names of all the .MP3 and .WMA found on a computer. It’s still up to you to contact each user and ask him or her to delete the offending files. That’s a lot of work on your part, and you then have to rely on the users deleting the files (without accidentally deleting something else in the process). So why not let the script save you all that trouble? This version not only tracks down all the .MP3 and .WMA files on a computer, it also deletes the files as they are found:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile where Extension = 'mp3' OR Extension = 'wma'")
For Each objFile in colFiles
   objFile.Delete 
Next

And remember, this works on remote computers just as quickly and just as easily as it does on the local computer. Just change the value of the variable strComputer to the name of the remote computer and have at it.