As a System Administrator, Care and Feeding of your servers is a crucial task. Imagine you have a directory containing daily transaction (substitute log, backup, or just about anything else) files. You need to keep these files for a period of time for auditing purposes, but space is limited and you don't want or need to keep them indefinitely. What is an Admin to do? Set a quarterly task to do general clean up? Yuck.
In Linux it is pretty easy to accomplish this task with the "find" command and its various switches. How do you do it on a Windows server? What I am about to show you works on Windows 2008 Servers. It may not work on Windows 2003 as I believe the syntax for our magic command "forfiles" was a little different.
Below is are the commands you need in a batch file to delete files and/or folders older than "x" days.
Open up notepad or your favorite Windows plain text editor (I like Notepad++ btw).
Enter the following text between the "-----" but not including the "-----"
--------------------------------------------------------
@echo off
rem - The following line is a cya testing line. It will display the files or
rem - folder that are older than "x" days but does not delete them.
rem - Where you see /d -x
rem - replace x with your criteria. I will use 30 do anything older than 30 days.
rem - also change your path. In this example, I want to clean up files in the
rem - E:\SharePointBackup directory older than 30 days.
rem - Uncomment the following "forfiles" line for testing,
rem - but make sure all other lines are commented out.
rem FORFILES /p "E:\SharePointBackup" /s /m *.* /d -30 /c "CMD /C ECHO @FILE"
rem - The following line will delete files older than "30" in given directory
rem - This will just delete files and not remove directories or anything else.
rem - Uncomment the following "forfiles" line to delete files older than 30 days, but make sure
rem - all other lines are commented out.
rem FORFILES /p "E:\SharePointBackup" /s /m *.* /d -30 /c "CMD /C del /Q @FILE"
rem - This will look for directories in a given path older than 30 days
rem - and delete it and all of its contents. All files and subdirectories in directories
rem - that are older than 30 days.
rem - Uncomment the following "forfiles" line to delete directories older than 30 days, but make sure
rem - all other lines are commented out.
rem FORFILES /p "E:\SharePointBackup" /d -30 /c "CMD /C if @isdir==TRUE RMDIR /S /Q @path"
----------------------------------------------------------------
Save this file on your server as whatever you want with a ".bat" extension. Example: delete_older_than_30.bat
Make sure you "test" this on data you wouldn't mind losing before putting it in production. Once you have tested and have verified it will do what you want it to do, you can schedule a daily (or whatever you'd like) task using the scheduler calling this batch file.
I hope this helps some of you out there.
Friday, April 6, 2012
Subscribe to:
Posts (Atom)