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

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


当前回答

Windows Server 2008 R2操作系统

forfiles /P c:\sql_backups\ /S /M *.sql /D -90 /C "cmd /c del @PATH"

这将删除所有超过90天的.sql文件。

其他回答

删除所有超过3天的文件

forfiles -p "C:\folder" -m *.* -d -3 -c "cmd  /c del /q @path"

删除超过3天的目录

forfiles -p "C:\folder" -d -3 -c "cmd  /c IF @isdir == TRUE rd /S /Q @path"

我的命令是

forfiles -p "d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE" 

@PATH -在我的例子中只是路径,所以我必须使用@PATH\@FILE

同样适用于文件/?对我来说也不行,但对于文件(没有“?”)工作得很好。

我唯一的问题是:如何添加多个掩码(例如“.log|.bak”)?

所有这些都是关于我在这里下载的forfiles.exe (win XP)

但如果你使用的是Windows服务器,forfiles.exe应该已经在那里,它是不同于ftp版本。这就是为什么我应该修改命令。

对于Windows Server 2003,我使用这个命令:

forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"

享受:

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

更多细节请参见forfiles文档。

要了解更多信息,请参考Windows XP命令行的A-Z索引。

如果您的计算机上没有安装forfiles,请将其从任何Windows Server 2003复制到您的Windows XP计算机的%WinDir%\system32\。这是可能的,因为EXE在Windows Server 2003和Windows XP之间完全兼容。

后续版本的Windows和Windows Server默认安装了它。

Windows 7及更新版本(包括Windows 10):

语法略有变化。因此更新后的命令为:

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

请允许我在这条已经很有价值的线索上再做一点小小的贡献。我发现其他解决方案可能会摆脱实际的错误文本,但忽略了%ERRORLEVEL%,这表明我的应用程序失败。并且我合理地想要%ERRORLEVEL%,只要它不是“没有找到文件”错误。

一些例子:

具体地调试和消除错误:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||echo found success

使用一个线性程序返回ERRORLEVEL成功或失败:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT /B 1||EXIT /B 0

在批处理文件的上下文中,在其他代码的中间使用一个线性程序来保持ERRORLEVEL为0 (ver > nul重置ERRORLEVEL):

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||ver > nul

对于SQL Server代理CmdExec作业步骤,我落在下面。我不知道这是否是一个错误,但该步骤中的CmdExec只识别第一行代码:

cmd /e:on /c "forfiles /p "C:\SQLADMIN\MAINTREPORTS\SQL2" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT 1||EXIT 0"&exit %errorlevel%

Windows Server 2008 R2操作系统

forfiles /P c:\sql_backups\ /S /M *.sql /D -90 /C "cmd /c del @PATH"

这将删除所有超过90天的.sql文件。