Solved

Script to delete files from a particular directory

Posted on 2014-02-13
3
228 Views
Last Modified: 2014-02-20
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?
0
Comment
Question by:LuiLui77
3 Comments
 
LVL 34

Accepted Solution

by:
Dan Craciun earned 500 total points
ID: 39857642
Try this:
gci -Path x:\your\path | %{ if($_.LastWriteTime -lt (Get-Date).AddDays(-7)) {$_.Delete()}}

Open in new window

HTH,
Dan
0
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39857951
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
 

Author Closing Comment

by:LuiLui77
ID: 39874085
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

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
The viewer will learn how to count occurrences of each item in an array.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question