批处理脚本删除最早的文件夹中的给定文件夹 [英] Batch Script to delete oldest folder in a given folder

查看:172
本文介绍了批处理脚本删除最早的文件夹中的给定文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个简单的.BAT备份脚本,而作为它的一部分我要最旧的备份(文件夹)在达到备份集的最大限制被删除。

I'm writing a simple .bat backup script, and as part of it I want the oldest backup (folder) to be deleted upon reaching a set max limit of backups.

现在我有这样的:

%计数器%是基于目前在备份的存储目录备份文件夹的数量,和较早在脚本计算

%COUNTER% is based on the number of backup folders currently in the directory where backups are stored, and is calculated earlier in the script.

%MAXBACKUPS%就像是10,用户指定的号码说,你只希望保留10个版本的备份。

%MAXBACKUPS% is just a user-specified number like "10," to say that you only want to keep up to 10 versions of the backups.

:: Delete the oldest backup, but only if we've exceeded the desired number of backups.
IF %COUNTER% gtr %MAXBACKUPS% (
ECHO More than %MAXBACKUPS% backups exist. Deleting oldest...
FOR /f "delims=" %%a in ('dir "..\Backup\*" /t:c /a:d /o:-d /b') do rd /s /q "..\Backup\%%a"
::Increment the counter down since we've just removed a backup folder.
SET /a COUNTER=%COUNTER%-1
)

我想这个脚本只删除 .. \\备份文件夹中的最古老的文件夹,但因为它的立场似乎删除它发现每一个文件夹到达极限备份,这显然是不期望的行为。

I would like this script to only delete the one oldest folder in the ..\Backup folder, but as it stands it seems to delete every single folder it finds once it reaches the backup limit, which is obviously not the desired behavior.

推荐答案

您是如此接近! : - )

You were so close ! :-)

所有你需要做的就是跳过第一个%MAXBACKUPS%时,按日期排序降序条目。你甚至都不需要你的 COUNTER 变量。

All you need to do is skip the first %MAXBACKUPS% entries when sorted by date descending. You don't even need your COUNTER variable.

:: Preserve only the %MAXBACKUPS% most recent backups.
set "delMsg="
for /f "skip=%MAXBACKUPS% delims=" %%a in (
  'dir "..\Backup\*" /t:c /a:d /o:-d /b'
) do (
  if not defined delMsg (
    set delMsg=1
    echo More than %MAXBACKUPS% found - only the %MAXBACKUPS% most recent folders will be preserved.
  )
  rd /s /q "..\Backup\%%a"
)

这篇关于批处理脚本删除最早的文件夹中的给定文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆