I am looking for a way to delete all files older than 7 days in a batch file. I\'ve searched around the web, and found some examples with hundreds of lines of code, and oth
Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.
net use Z: /delete
net use Z: \\unc\path\to\my\folder
forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as
net use Z: \\unc\path\to\my\folder
if %errorlevel% equ 0 (
forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
) else (
echo "Z: is already in use, please use another drive letter!"
)
For Windows Server 2008 R2:
forfiles /P c:\sql_backups\ /S /M *.sql /D -90 /C "cmd /c del @PATH"
This will delete all .sql files older than 90 days.
forfiles /p "v:" /s /m *.* /d -3 /c "cmd /c del @path"
You should do /d -3
(3 days earlier) This works fine for me. So all the complicated batches could be in the trash bin. Also forfiles
don't support UNC paths, so make a network connection to a specific drive.
You might be able to pull this off. You can take a look at this question, for a simpler example. The complexity comes, when you start comparing the dates. It may be easy to tell if the date is greater or not, but there are many situations to consider if you need to actually get the difference between two dates.
In other words - don't try to invent this, unless you really can't use the third party tools.
Use forfiles.
There are different versions. Early ones use unix style parameters.
My version (for server 2000 - note no space after switches)-
forfiles -p"C:\what\ever" -s -m*.* -d<number of days> -c"cmd /c del @path"
To add forfiles to XP, get the exe from ftp://ftp.microsoft.com/ResKit/y2kfix/x86/
and add it to C:\WINDOWS\system32
If you have the XP resource kit, you can use robocopy to move all the old directories into a single directory, then use rmdir to delete just that one:
mkdir c:\temp\OldDirectoriesGoHere
robocopy c:\logs\SoManyDirectoriesToDelete\ c:\temp\OldDirectoriesGoHere\ /move /minage:7
rmdir /s /q c:\temp\OldDirectoriesGoHere