Windows – Using FORFILES to delete Folders older than 2 days

batchcommand linewindows 7

here is what i'm trying to do:

Use the forfiles Command in a .cmd script to delete folders from a specified path that are older than e. g. 2 days on a win7 machine.

Edit: The Situation is the following under the path X:\backups are folders which contain daily backups e. g. 25.06.2014 next folder 24.06.2014 and so on.

My questions regarding this are now:

  • /d in the help it always stresses –files–. So I'm not sure if this works for folders too.
  • especially i'm not sure what it would do in combination with /s. So it would just run through the folders and delete the files – but what if already the parentfolder was too old? On a sidenote the whole concept of recursive is not clear to me and what it means i was not able to find out. It just means going through the folders right?
  • If i would go with an IF-Statement then i would have to use 2 Variable @ISDIR and @FDATE. With this solution i don't know how to combine 2 If-Statements in the forfiles command and additionally i'm not sure if @FDATE is again only for files and not folders.

So how to do it right?

Reference of forfiles:
http://technet.microsoft.com/de-de/library/cc753551%28v=ws.10%29.aspx

Greetings!

Best Answer

Solution

Despite its name, the forfiles command is able to handle both files and folders. Here's a batch script that does the job:

@echo off
setlocal

set target=X:\backups
set days=-2

for /f "usebackq delims=" %%G in (
`forfiles /p "%target%" /c "cmd /c if /i @isdir == true echo @path" /d %days% 2^>nul`
) do echo rd /s /q "%%~G"

pause
endlocal & exit /b

How it works

First of all, the target and days variables are initialized. The first one is set to the folder you want to scan, and the latter is the amount of days. Negative values mean older than or equal.

The forfiles command is then run by specifying the folder and number of days that were set earlier. For each result, the special @isdir variable is checked: if the value is true the current entry is a folder, and its @path is echoed. The command output is then parsed to get all matching folders and delete them. For safety reasons, there's an extra echo command so you can check whether the right folders are removed.

When using the recursive switch (/s), all files, folders, and their subfolders are processed. In this case you don't want to; otherwise you might end up deleting old subfolders contained in newer folders, which shouldn't be touched at all.

Further reading

Related Question