algorhythm February 2016

Deleting a file that is older than x number of days using a batch file in Windows

I have been trying to write a batch file that removes files that are older than x number of days. I have a backup directory E:\Backup2 that contains a number of sub-folders Alresco, Postgres and Sybase.

These sub-folders contain different internal structuring of files but I don't think this should affect the script as I only need it to look through every file in the Backup2 directory, and if it is older than x days then delete that file.

So far I have the following but I cannot get it to work:

FORFILES /P "E:\Backup2" /S /D -2 /C "CMD DEL /F /Q @PATH"

where 2 defines how old a file must be in days before it can be deleted.

When I execute the command in CMD all of the files remain without any error being reported.

What is interesting however is that when I output to a log file, it reports the directory where the first file is located..

When I first ran the command the log file reported E:\Backup2\Alfresco\25072015 however when I moved a log file to the root directory and re-ran the comman the log file reported E:\Backup2 which suggests the command is finding the first log file it needs to delete and then breaks.

Answers


Melis February 2016

From the documentation found here they have these examples:

    Examples:

Delete the testfile if it is is 5 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -5

Find .xls file that were last modified 30 days ago or older 
C:\> FORFILES /M *.xls /C "cmd /c echo @path was changed 30 days ago" /D -30

List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C "cmd /c echo @fsize"

Compared to your code you seem to miss /c when calling cmd del, so your code should be:

FORFILES /P "E:\Backup2" /S /D -2 /C "CMD /c DEL /F /Q @PATH"

Post Status

Asked in February 2016
Viewed 3,285 times
Voted 8
Answered 1 times

Search




Leave an answer