Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Script to delete files from a particular directory

Posted on 2014-02-13
3
Medium Priority
?
245 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 35

Accepted Solution

by:
Dan Craciun earned 2000 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 57

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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. 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

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
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…

719 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