swade1987
swade1987

Reputation: 1673

Batch Script: Delete folder and it's contents created over X days ago

I have a backup folder containing a bunch of folders and .zip files.

I basically want to create a batch script (which runs nightly) that deletes all folders (and their contents) which were created X days or more ago.

I tried the following FORFILES command however it just deletes file but not folders:

@echo off
:: set folder path
set dump_path=C:\Users\sw\Desktop\Test

:: set min age of files and folders to delete
set max_days=1

:: remove files from %dump_path%
forfiles -p %dump_path% -m *.* -d -%max_days% -c "cmd  /c del /q @path"

:: remove sub directories from %dump_path%
forfiles -p %dump_path% -d -%max_days% -c "cmd /c IF @isdir == TRUE rd /S /Q @path"

Looking forward to your help.

Steven

Upvotes: 1

Views: 1925

Answers (1)

PA.
PA.

Reputation: 29339

See this example using ROBOCOPY to move the files older than 7 days to a trash folder and then delete them.

MD %temp%\trash
ROBOCOPY %src% %temp%\trash /MOVE /E /MINAGE:7
RD %temp%\trash /s

Edit added /E switch to recurse directories

Upvotes: 1

Related Questions