script to delete old files in server folders after a week

Davidfoley used Ask the Experts™

We have an FTP server with users with multiple folders. The requirement is that users delete the old files after a week,
I am looking at doing this automatically,
Does anyone know if this can be done is power shell or a batch script, that will go to a folder or sub folders, look for files older than a week and delete them


Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ganesh AnandLead Technical Consultant

save as cleanup.cmd or cleanup.bat

You need to modify the line 2 to specify the top level folder.
@echo off
set topLevel=d:\some\directory
cd /D %topLevel%
FOR /D %%a IN (*) DO (
forfiles /P "%topLevel%\%%a" /S /M *.* /D -7 /C "cmd /C del @PATH"
cd /D %topLevel%\%%a
for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do rd "%%i">NUL
Director of Information Technology
If you want Powershell here is another option.
get-childitem -path '\\ftpserver\Clients' -recurse | where {$_.lastwritetime -lt (get-date).adddays(-7) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force}

Open in new window

Schedule this to run daily with a Scheduled Task

powershell.exe 'DeleteFTP.ps1'
Bill PrewIT / Software Engineering Consultant
Top Expert 2016

Why not just use a small free utility called DELAGE for this, it's a great tool, that I use often.

Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.


if the directory folder names are different is there a select all command

set topLevel=d:\some\directory  

e.g   c:\ftp\ftp_users\jakeholland

where there could be a hundred different usernames, but I want to delete all files in each users directory without running the script for each user.
yo_beeDirector of Information Technology

The powershell script I supplied for you does not care about the folder structure, but the age of the file.

I am not sure if you need to be concerned with folders since you are looking for file ages.
Bill PrewIT / Software Engineering Consultant
Top Expert 2016

The /recurse switch with DELAGE accomplishes this.

find LOCATION -not -mtime 6 -delete
deletes all the files which have not been modified in the past 7 days

if you are running windows, versions of the find command for windows are available in cygwin, in findutils ( and in various other places. the builtin find command in windows does not have such capabilities afaik

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial