Recipe 8.22. Performing an Action on Several Files at Once


Problem

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

Solution

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 -pd:\ -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 -h for the Windows 2000 version (used above) and forfiles /h for the Windows Server 2003 version. The two versions vary slightly.

Using VBScript
' This code shows how to iterate over all the zip files on a system ' ------ SCRIPT CONFIGURATION ------ strComputer  = "." strExtension = "zip" ' ------ END CONFIGURATION --------- set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 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 next WScript.Echo "Total: " & intCount

Discussion

If you aren't familiar with the forfiles command, we highly recommend that you check it out. We don't know how many times we'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.



Windows XP Cookbook
Windows XP Cookbook (Cookbooks)
ISBN: 0596007256
EAN: 2147483647
Year: 2006
Pages: 408

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net