[英]How do you create a batch script that will delete the oldest files when a folder size limit is reached
我已经找到了许多解决类似问题的解决方案,但是我不知道是否可以创建一个脚本,以在达到预设的文件夹大小限制后删除最旧的文件?
You need to solve two problems. 您需要解决两个问题。
First, you need to calculate the folder size. 首先,您需要计算文件夹的大小。 Use a code similar to this
使用与此类似的代码
:foldersize
set sz=0
for %%F in (%1\*.*) do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
echo %%F %%~zF !kb! !sz!
)
goto :eof
Second, you need to recognize older files and delete them until a size is reached 其次,您需要识别较旧的文件并删除它们,直到达到大小为止
for /F "tokens=*" %%F in ('dir /A-D /OD /B %1\*.*') do (
if !sz! geq !targetsize! (
call :filesize %1\%%F
del %1\%%F
set /a sz = !sz! - !kb!
) else (
goto :eof
)
)
goto :eof
:filesize
set /a kb = %~z1 / 1024
goto :eof
Putting all pieces together... 将所有零件放在一起...
@echo off
setlocal enabledelayedexpansion
set /a targetsize=%2
call :foldersize %1
for /F "tokens=*" %%F in ('dir /A-D /OD /B %1\*.*') do (
if !sz! geq !targetsize! (
call :filesize %1\%%F
del %1\%%F
set /a sz = !sz! - !kb!
) else (
echo Done... %1 size is now !sz! KB
goto :eof
)
)
echo Not completely done... %1 size is still !sz! KB
goto :eof
:filesize
set /a kb = %~z1 / 1024
goto :eof
:foldersize
set sz=0
for %%F in (%1\*.*) do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
)
goto :eof
Test and test and test, as it does not move the files to the trash but it deletes the files permanently. 测试并测试,因为它不会将文件移到回收站,但会永久删除文件。
Also, you may want to specify /F
option in case you have read-only files you want to delete. 另外,如果您有要删除的只读文件,则可能要指定
/F
选项。
In the case you have subfolders in the folder and you want to take those into the account of folder size and you want to delete the older files, things may get more complicated. 如果文件夹中有子文件夹,并且您想将这些文件夹考虑到文件夹大小中,并且想要删除较旧的文件,则情况可能会变得更加复杂。
The calculation of the size is this 尺寸的计算是这个
:foldersizerecurse
set sz=0
for /F %%F in ('dir /OD /B *.*') do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
echo %%F %%~zF !kb! !sz!
)
goto :eof
And deleting the older files.. you need to pipe the 'dir /S' command output to sort and sort by date. 并删除较旧的文件..您需要通过管道'dir / S'命令输出来对日期进行排序和排序。 I feel tired to do it.
我觉得很累。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.