4.22. Performing an Action on Several Files at Once


You want to perform an action on several files at once.


Using a command-line interface

The forfiles.exe utility is a handy tool that lets you search and iterate over a group of files and perform an action against them. For example, this command searches the d:\ drive for all files with a .zip extension and prints out the name of each file and its size:

> forfiles /p d:\ /s /m *.zip /c "cmd /c echo @file : @fsize"

Here is another example that opens everything that ends in .txt with notepad. It performs a check to make sure only files are opened, not directories (@isdir= =FALSE):

> forfiles /m *.txt /c "cmd /c if @isdir=  =FALSE notepad.exe @file"

For more information about the command-line options forfiles supports, run forfiles /? for the Windows Server 2003 version and forfiles -h for the Windows 2000 version. The two versions vary slightly.

Using VBScript

' This code shows how to iterate over all the zip files on a system
strComputer  = "."
strExtension = "zip"
' ------ END CONFIGURATION ---------
set colFiles = objWMI.ExecQuery("select * from Cim_DataFile " & _
                             " where extension = '" & strExtension & "'")
WScript.Echo "Files with a ." & strExtension & " extension:"
intCount = 0
for each objFile in colFiles
   WScript.Echo "   " & objFile.Name
   ' Do some action here
   intCount = intCount + 1
WScript.Echo "Total: " & intCount


If you aren't familiar with the forfiles command, I highly recommend that you check it out. I don't know how many times I've had to write a script or piece together a long command line to iterate over a series of files and perform some action. Forfiles makes the process much easier.

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.