Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to delete the oldest and second eldest folder from a drive using a Windows Command Line script.

This is running from BackupAssist, which only supports windows command line commands/DOS in the GUI for pre or post-backup scripts. I'd rather not write a command line to call into a Powershell script.


share|improve this question
up vote 2 down vote accepted

This will find the oldest and next oldest directories in the current directory. Comment out the echo commands and uncomment the rd commands to make it functional.

@echo off
rem cmd file to delete oldest and second oldest directories
setlocal enabledelayedexpansion
for /F "delims=" %%i in ('dir /b/ad-l/o-d') do @set nextoldest=!oldest! & SET oldest=%%i
echo %oldest%
echo %nextoldest%
rem rd /s/q %oldest%
rem rd /s/q %nextoldest%

If you want to make it look at the whole drive, change the dir command to look like this:

dir /b/ad-l/o-d/s \

That will take a long time.

Note that I excluded junction points with -l.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.