简体   繁体   中英

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.

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. I feel tired to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM