开发者

Batch file to delete old and different folders in a directory

I want to write a DOS batch file to delete old folders in a directory but keep the newest folder. Here is a sample of my folders under D:\m开发者_开发知识库yfolders\:

Jack_20110507  (previous day time-stamped folder)
Jack_20110508  (current day time-stamped folder)
James_20110507
James_20110508 
Kenny_20110507
Kenny_20110508
...

I would like to delete all previous day time-stamped folders *_20110507, but keep all current day time-stamped folders *_20110508. New timestamped folders are created daily.


The script below will get the current local date in YYYYMMDD (courtesy of this answer).

It then loops through all the folders in a given directory (In my case this was a test sub folder beneath the folder containing the script) and checks the last 8 characters of the folder name. If they do not match today's date, it deletes the folder.

The /Q disables the confirmation for folder deletion. If you want to be prompted for confirmation before a folder is deleted, remove this.

@ECHO off & setlocal EnableDelayedExpansion

REM Get the local datetime
FOR /F "usebackq tokens=1,2 delims==" %%i IN (`wmic os get LocalDateTime /VALUE 2^>NUL`) DO IF '.%%i.'=='.LocalDateTime.' SET ldt=%%j

REM Set the datetime to YYYYMMDD format.
SET today=%ldt:~0,4%%ldt:~4,2%%ldt:~6,2%

REM For every file in the folder test:
FOR /D %%f IN (.\test\*) DO (
    REM Store the folder name temproarily
    SET folder=%%f
    REM Get just the ending date part of the folder name
    SET folderpart=!folder:~-8!
    REM If it doesn't match todays date, delete the folder.
    IF NOT !folderpart!==!today! RD /Q %%f
)
@ECHO ON


I wouldn't use a batch script for anything other than the very simplest stuff.

I recommend you look at a scripting language such as Python.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜