Script to delete files from a particular directory

I am looking to automate the deletion of files on a particular directory. These files are created daily and I will need to delete all files except for the last 7 (last 7 days).

Does anyone has an idea on how to accomplish this?
LuiLui77Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Dan CraciunConnect With a Mentor IT ConsultantCommented:
Try this:
gci -Path x:\your\path | %{ if($_.LastWriteTime -lt (Get-Date).AddDays(-7)) {$_.Delete()}}

Open in new window

HTH,
Dan
0
 
Bill PrewCommented:
Here's a relatively simple BAT script approach. Sorts the files newest to oldest, and skips the 7 most recent and deletes the rest.

@echo off
for /f "tokens=* skip=7" %%A in ('dir /b /o-d /a-d "c:\temp\*.*"') do del "%%~A"

Open in new window

~bp
0
 
LuiLui77Author Commented:
Hey Dan, thank you for the command line it worked perfectly.

Since I will use this command line on a 2003 server, I had to install Powershell 2.0 first.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.