0

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:\myfolders\:

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.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
trukip
  • 1
  • 1
  • You can get the current date with `for /f "skip=1 delims=" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x` and you'd need a bit date math, then. It gets a bit longer, though. – Joey May 19 '11 at 14:47

2 Answers2

1

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
Community
  • 1
  • 1
staticbeast
  • 2,073
  • 2
  • 22
  • 24
0

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.

MRAB
  • 20,356
  • 6
  • 40
  • 33