我有一个脚本,它将从嵌套文件结构中删除超过31天的所有文件。
在某些时候,它会留下空文件夹,我正在寻找一种方法来删除它们,理想情况下保留比31天更新的文件夹。鉴于rd FolderName
如果文件夹不为空,则不会删除该文件夹,我可以使用它来删除文件夹。问题是,如果我这样做,它将不会删除所有空文件夹,只删除树中最深的文件夹。如果我可以反转文件列表给我,它会工作。如果那是不可能的,还有另一种方式吗?
注意:rd / s不仅会删除嵌套的文件夹,还会删除其文件。如果文件夹不为空,我不想删除它。
这是我的剧本:
@echo off
cd /d "C:\MyPath"
:: remove files that are older than 31 days (retention period)
forfiles /s /d -31 /c "cmd /c if @isdir==FALSE del @relpath")
:: attempt to remove folders (will fail if the folder is not empty.)
forfiles /s /d -31 /c "cmd /c if @isdir==TRUE rd @relpath"
以上脚本只会删除最深的文件夹。我想我可以连续8次执行forfiles,但这是对资源的严重浪费。
答案 0 :(得分:1)
对于删除no内容目录,@ Magoo已经隐含的内容比你自己的答案更好,更快:
FOR /F "DELIMS=|" %%A IN ('DIR/B/S/AD-S-L^|SORT/R') DO RD "%%A" 2>NUL
答案 1 :(得分:0)
在@Magoo的帮助下,他指出我可以使用sort / r来反转列表,我设法找到了解决方案。
使用的代码如下:
@echo off
cd /d "C:\MyPath"
:: remove files that are older than 31 days (retention period)
forfiles /s /d -31 /c "cmd /c if @isdir==FALSE del @relpath")
:: attempt to remove folders (will fail if the folder is not empty.)
for /f %%i IN ('forfiles /s /d -31 /c "cmd /c if @isdir==TRUE echo @relpath" ^|sort /r') DO rd %%i