我正在寻找一种方法来删除批处理文件中超过7天的所有文件。我在网上搜索了一下,找到了一些包含数百行代码的示例,还有一些示例需要安装额外的命令行实用程序来完成任务。

在BASH中,只需几行代码就可以完成类似的工作。在Windows中,似乎可以为批处理文件做一些简单的事情。我正在寻找一个解决方案,工作在标准的Windows命令提示符,没有任何额外的实用程序。请不要使用PowerShell或Cygwin。


当前回答

使用forfiles。

有不同的版本。早期使用unix风格的参数。

我的版本(用于服务器2000 -注意交换机后面没有空格)-

forfiles -p"C:\what\ever" -s -m*.* -d<number of days> -c"cmd /c del @path"

要将forfiles添加到XP,请从ftp://ftp.microsoft.com/ResKit/y2kfix/x86/获取exe

并将其添加到C:\WINDOWS\system32

其他回答

这一个帮我做到了。它有一个日期,你可以减去想要的数量,回到过去的时间:

@echo off

set m=%date:~-7,2%
set /A m
set dateYear=%date:~-4,4%
set /A dateYear -= 2
set DATE_DIR=%date:~-10,2%.%m%.%dateYear% 

forfiles /p "C:\your\path\here\" /s /m *.* /d -%DATE_DIR% /c "cmd /c del @path /F"

pause

cmd /c del @path /F中的/F强制删除特定文件,在某些情况下,该文件可以是只读的。

dateYear是年份变量,您可以根据自己的需要更改减号

看看我对类似问题的回答:

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"

这将删除比给定日期更早的文件。我相信它可以被修改为从当前日期往回走7天。

更新:我注意到HerbCSO已经改进了上面的脚本。我建议改用他的版本。

使用forfiles。

有不同的版本。早期使用unix风格的参数。

我的版本(用于服务器2000 -注意交换机后面没有空格)-

forfiles -p"C:\what\ever" -s -m*.* -d<number of days> -c"cmd /c del @path"

要将forfiles添加到XP,请从ftp://ftp.microsoft.com/ResKit/y2kfix/x86/获取exe

并将其添加到C:\WINDOWS\system32

复制这段代码并保存为DelOldFiles.vbs。

使用CMD: cscript //nologo DelOldFiles。于六月15日

“15”表示删除超过15天的文件。

  'copy from here
    Function DeleteOlderFiles(whichfolder)
       Dim fso, f, f1, fc, n, ThresholdDate
       Set fso = CreateObject("Scripting.FileSystemObject")
       Set f = fso.GetFolder(whichfolder)
       Set fc = f.Files
       Set objArgs = WScript.Arguments
       n = 0
       If objArgs.Count=0 Then
           howmuchdaysinpast = 0
       Else
           howmuchdaysinpast = -objArgs(0)
       End If
       ThresholdDate = DateAdd("d", howmuchdaysinpast, Date)   
       For Each f1 in fc
     If f1.DateLastModified<ThresholdDate Then
        Wscript.StdOut.WriteLine f1
        f1.Delete
        n = n + 1    
     End If
       Next
       Wscript.StdOut.WriteLine "Deleted " & n & " file(s)."
    End Function

    If Not WScript.FullName = WScript.Path & "\cscript.exe" Then
      WScript.Echo "USAGE ONLY IN COMMAND PROMPT: cscript DelOldFiles.vbs 15" & vbCrLf & "15 means to delete files older than 15 days in past."
      WScript.Quit 0   
    End If

    DeleteOlderFiles(".")
 'to here

更灵活的方法是使用FileTimeFilterJS.bat:

@echo off

::::::::::::::::::::::
set "_DIR=C:\Users\npocmaka\Downloads"
set "_DAYS=-5"
::::::::::::::::::::::

for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat  "%_DIR%" -dd %_DAYS%') do (
    echo deleting  "%%~f#"
    echo del /q /f "%%~f#"
)

该脚本将允许您使用诸如日、分、秒或小时等测量。 选择weather按创建、访问或修改时间筛选文件 列出某个日期之前或之后(或两个日期之间)的文件 选择是显示文件还是dirs(或两者都显示) 递归与否