In a large directory, I need to delete all the files over 1 year old. I know that I could use Robocopy's /MINAGE:n switch to move the old files to another directory, where I could delete them with the Del command. However, I was wondering whether there's a way to use Robocopy to delete the old files directly, without moving them first.
No, Robocopy doesn't have that capability, so you'll need to take another approach. The Dir command is useful for capturing the last modified date for a file. However, once you have that date, it's difficult to do the math to determine the file's age. You would have to write a lot of code to convert the date into a format that the command-shell math functions could use.
A better way is to use the Forfiles tool, which you can find in the Windows resource kits. Forfiles lets you perform a date-based deletion. Here's a sample command:
Forfiles -p R:\MyFiles -s -m *.* -d -365 -c "Cmd /C Echo 0x22@Path\@File0x22"
(Although this command appears on several lines here, you'd enter it on one line in the command-shell window. The same holds true for the other multiline commands in this article.) In this command, the -p switch specifies the location in which to start searching, and the -s switch tells Forfiles to search subdirectories. You use the -m switch to tell Forfiles the types of files to search for. The default value of *.* tells Forfiles to search for files of all types. You use the -d switch to specify the age or age range of the files in which you're interested. The -d -365 switch tells Forfiles to search for files 365 days or older. Finally, you use the -c switch to tell Forfiles what to do with the files that meet your search criteria. For each file that meets the criteria, Forfiles will run the specified command. Note that you must enclose commands with spaces in quotes.
In the sample command, you might have noticed that the command Forfiles will run is displaying rather than deleting the files that are 1 year old or older. Any code that performs mass deletions or another potentially destructive operation must be tested extensively before implementing it in a production environment. I like to use the Echo command instead of the Del /q command in these situations. (The /q switch tells the Del command to delete files without confirmation.) That way, I see exactly what I'll be deleting.
For more information about Forfiles' switches and its usage possibilities, see the tool's online Help file. If you're interested in a deletion approach that uses a Perl script, check out "Real-World Scripting: Deleting Files by Their Age," June 2000, InstantDoc ID 8799.