22 January 2013

Easily schedule deletion of older files in a particular folder

In a previous post http://raunomagi.blogspot.com/2012/05/how-to-delete-files-older-than-x-days.html I revealed how to delete older files, but some folder keep growing up and need regular cleaning.

Let’s assume, that the folder, that is growing is IIS web logging in folder C:\inetpub\logs\LogFiles\W3SVC1 (this can be any folder, but to make it more realistic I use this one). To check, how big this folder is right now, use this PowerShell command:

dir C:\inetpub\logs\LogFiles\W3SVC1 | measure -sum length

image

It’s not easily readable, but I see 150 files using 29GB of disk space.

For scheduled deletion you need only few lines to paste into administrative command prompt:

  1. echo forfiles /d -50 /p C:\inetpub\logs\LogFiles\W3SVC1 /c "cmd /c del @path" > %windir%\DeleteOldFiles.bat
  2. schtasks /create /RU:"" /SC:DAILY /TR "'%windir%\DeleteOldFiles.bat'" /ST:01:00 /RL:HIGHEST /TN:DeleteOldFiles
  3. schtasks /run /TN:DeleteOldFiles

image

Line 1 creates a file in Windows directory named DeleteOldFiles.bat. If your directory is somewhere else, change it accordingly. If the path to the folder includes spaces, surround it with quotation marks. The .BAT file looks like this:

image

Line 2 creates a scheduled task for running the .BAT file under SYSTEM account daily at 01:00. The task can be modified later on Task Scheduler:

image

Line 3 run’s the scheduled task right away.

After running the task I returned to my PowerShell window and rechecked the result:

image

So it seems, like I got almost 20GB of free space Smile

No comments:

Post a Comment