批处理文件,删除目录中除最新文件夹外的所有文件夹 [英] Batch file to delete all folders in a directory except the newest folder

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

问题描述

完成新备份后,我正在尝试删除特定文件夹中的旧备份.由于我实际上没有DOS命令的经验,因此将在互联网上找到的两个脚本混为一谈:

I am trying to delete old backups in a specific folder after a new backup has been done. As i do not really have experience with DOS commands i mashed a couple of scripts i found on the internet into one:

::(C)2008 "BuckFix" www.winsupportforum.de
@echo off
setlocal

set workdir="M:\BACKUPS\CACHE_SSD\"
set folder=
:: get list of all folders, oldest first
dir %workdir% /AD /B /t:w /OD > %temp%folder.tmp
for /f "tokens=1* delims=" %%i in (%temp%folder.tmp) do set "folder=%%i"
del %temp%folder.tmp

::checking if its the right one...just for debugging
echo newest... %folder%

set filedir="M:\BACKUPS\CACHE_SSD\%folder%"

::delete all folders except %folder% ...but how?

pause

因此,选择最新的文件夹效果很好,但我不知道如何删除除该文件夹以外的所有文件夹.我认为这只是一个简单的for循环,但到目前为止,我的所有尝试均以失败告终. 它必须是一种安全的方法,因为它是一个备份文件夹,我只想保留最新的备份.我有可以工作的删除脚本,但是当只有一个文件夹时,它也会删除该脚本.当目录为空时,它将杀死整个目录.

So picking the newest folder works fine but i don't know how to delete all folders except that one. I think it'll just be a simple for-loop but all my attempts failed so far. It has to be a safe method as it is a backup folder and i just want to keep the most recent backup. I had delete scripts that worked but when there was only one folder it deleted that one as well. And when the directory was empty it killed the whole directory.

推荐答案

@echo off
setlocal

set "workdir=M:\BACKUPS\CACHE_SSD\"
set "folder="
for /f "tokens=* delims=" %%i in ('dir %workdir% /AD /B /TW /O-D') do (
    set "folder=%%~fi"
    goto :break
)
:break
echo newest... %folder%

for /f "skip=1 tokens=* delims=" %%i in ('dir %workdir% /AD /B /TW /O-D') do   (
    echo rd /s /q "%%~fi"
)

pause

对此进行测试.回显实际的删除命令.如果一切正常,请在echo rd /s /q "%%~fi"中删除echo.

Test this.Actual removing command is echoed .Delete echo in echo rd /s /q "%%~fi" if everything is ok.

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

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