Saturday, October 27, 2012

Batch file to delete files older than N days in Windows command line

http://stackoverflow.com/questions/51054/batch-file-to-delete-files-older-than-n-days
http://ss64.com/nt/forfiles.html
http://ss64.com/nt/syntax-delolder.html

My command is
forfiles -p"d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE"
@PATH - is just path in my case, so I had to use @PATH\@FILE
also forfiles /? not working for me too, but forfiles (without "?") worked fine.
And the only question I have: how to add multiple mask (for example ".log|.bak")?
All this regarding forfiles.exe that I downloaded here: ftp://ftp.microsoft.com/ResKit/y2kfix/x86/ (on win XP) But if you are using windows server forfiles.exe should be already there and it is differs from ftp version... that is why I should modify command...
For windows server 2003 I'm using this command:
forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"
ลิสไฟล์ของพาธ d:\Backup เฉพาะ ไฟล์ที่ลงท้ายด้วย .log และ เก่ากว่า 15 วันแล้ว จากนั้น execute คำสั่ง delete ไฟล์ที่ลิสออกมา ...

------------------------------------------------------------------------------------------------
Delete files older than N days
There are several ways to do this

1) Using ForFiles to delete files over 7 days old, the syntax varies slightly according the version of ForFiles your machine has installed:
C:\> forfiles /p "C:\source_folder" /s /m *.* /c "cmd /c Del @path" /d -7
C:\> forfiles -p "C:\source_folder" -s -m *.* -c "cmd /c Del @path" -d 7
C:\> forfiles -p"C:\source_folder" -s -m*.* -c"cmd /c Del @path" -d7

2) Using Robocopy /Move to delete files over 7 days old:

C:\> set _robodel=%TEMP%\~robodel
C:\> MD %_robodel%
C:\> ROBOCOPY "C:\source_folder" %_robodel% /move /minage:7
C:\> del %_robodel% /q

3) Using DateMath.cmd and Getdate.cmd, download DelOlder.cmd

4) With PowerShell delete files over 7 days old:
PS C:\> $now = get-date
PS C:\> dir "C:\source_folder\" | where {$_.LastWriteTime -le $now.AddDays(-7)} | del -whatif


No comments:

Post a Comment

Popular Posts