我用这个脚本:
//////////////////////////////////////////////////////// // Deletes file older than a number of days // in the current directory //////////////////////////////////////////////////////// // Usage: wscript DeleteOlderThan.js [#Days] // By default, remove files older than 30 days //////////////////////////////////////////////////////// function removeDays(date, nDays) { var dateRet = date return dateRet.setDate(date.getDate() - nDays); } function addSlash(strPath) { var c = strPath.substr(-1, 1); if( c !== '\\' && c !== '/' ) { strPath += '\\'; } return strPath; } // Read arguments var nDays = WScript.Arguments(0) || 30; // Create system objects var fs = WScript.CreateObject("Scripting.FileSystemObject"); var shell = WScript.CreateObject("WScript.Shell"); // Retrieve current directory var strDirectoryPath = addSlash(shell.CurrentDirectory); // Compute date var dateNow = new Date(); var dateTest = removeDays(dateNow, nDays); // Iterate on files var folder = fs.GetFolder(strDirectoryPath); var files = folder.Files; for( var it = new Enumerator(files); !it.atEnd(); it.moveNext() ) { var file = it.item(); if( file.DateLastModified < dateTest) { file.Delete(true); } }
我每天都用以下方式调用:
wscript "C:\Program Files\Utils\DeletesOlderThan.js" 30
如果您使用的是Windows Server和/或安装了Server Resource Kit,那么forfiles可能正是您所需要的.
示例:打印超过180天的所有文件名
forfiles /S /D -180 /C "cmd /C Echo @Path" >olderthan180days.txt
删除超过365天的所有PDF文件
forfiles /S /M *.pdf /D -365 /C "cmd /C Del @Path"
编辑:我想通了.
要删除超过给定日期的所有文件:
REM del_old.bat REM usage: del_old MM-DD-YYY for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"
要删除比给定日期更新的所有文件:
REM del_new.bat REM usage: del_new MM-DD-YYYY for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist "%%~nxa" del "%%~nxa"
eJames:我发现你的xcopy解决方案工作得非常好!我最喜欢它的是它应该在除英语之外的Windows语言版本中工作,因为XCOPY参数的格式似乎与日期设置无关.精彩!]
一个改进是预先创建FILES_TO_KEEP.TXT文件,这样如果没有文件与保留条件匹配,第二个XCOPY语句仍然可以继续执行删除(如果它找不到FILES_TO_KEEP.TXT文件则失败).这是我的脚本(请注意在这个例子中我将其更改为仅删除*.pdf文件,我还更改了临时文件名,以确保没有潜在的冲突,以及之后清理临时文件):
@echo off SET OLDERTHAN=%1 IF NOT DEFINED OLDERTHAN GOTO SYNTAX echo >> ~~~FILES_TO_KEEP.TXT~ for /f "tokens=*" %%a IN ('xcopy *.pdf /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> ~~~FILES_TO_KEEP.TXT~ for /f "tokens=*" %%a IN ('xcopy *.pdf /L /I /EXCLUDE:~~~FILES_TO_KEEP.TXT~ null') do if exist "%%~nxa" del "%%~nxa" del ~~~FILES_TO_KEEP.TXT~ GOTO END :SYNTAX ECHO. ECHO USAGE: ECHO DELOLD mm-dd-yyyy ECHO Where mm-dd-yyyy is the date prior to which you want to delete files. ECHO. ECHO EX: "DELOLD 10-17-2008" Deletes files older than October 17, 2008. ECHO. ECHO This should work on any language version of Windows, but has only been ECHO tested in English-US versions. GOTO END :END