How to Delete Old IIS Log Files

Old Files

A couple of months ago I was asked to look into the ability to delete old IIS log files from the company’s Windows Server 2003 servers. These files were taking a great deal of disk space. This was at first a daunting task for me because I didn’t know of a DOS command that would do the trick. In the old MS-DOS 5.x and 6.x days, Microsoft had a very useful command called deltree, which saved me a lot of work when I wanted to delete an entire directory and its sub-directories. I don’t know why it was removed from Windows NT and its successors. Anyhow, a quick search on Google led me to an awesome Windows Server command called forfiles. I found out in another website how to use this command to delete files from a particular folder. If I can find that original webpage’s URL, I’ll post it here. In the meantime, I used the code as the basis for writing my own batch file program, which I am calling DeleteOldFiles. Not so creative, but it gets to the point.

DeleteOldFiles runs on Windows Server 2003. It should run on later versions. I can’t confirm because I don’t have access to a later version of it. Its usage syntax is as follows:

deleteoldfiles.bat [starting-directory] [file-mask] [age]

where:

  • [starting-directory]: Directory path where the delete operation will begin. Files are deleted recursively.
  • [file-mask]: The file name pattern to use. Wild cards (*) allowed. The single wild card character “*” and the wild card “*.*” are not permitted for security purposes.
  • [age]: A number (in days) between 0 and 32768 that specifies the age of the files to delete. The file’s last modified date is used. Therefore, any files whose last modified date is less than or equal to the (current date minus [age]) will be deleted. Default value is 182 (approx. 6 months).

Examples:

The following example deletes all files named “ex*.log” that were last modified over 1 year (365 days) ago. The starting directory is C:\Windows\System32\LogFiles:

deleteoldfiles.bat C:\Windows\System32\LogFiles ex*.log 365

The following example searches all subdirectories in C:\Windows and deletes all files named “dump.txt” that were last modified over 60 days ago:

deleteoldfiles.bat C:\Windows dump.txt 60

Source Code:

The source code is provided “as is” without warranties of any kind, expressed or implied. By copying/downloading it you accept and acknowledge that you shall not hold Mario Vargas liable for any damages. Use at your own risk.

The batch file script is being used by my employer’s Web servers and it’s executed every week.

@echo off

rem This batch file program deletes old files by starting path, file name pattern and age.
rem Type deleteoldfiles.bat at the command prompt for usage information.

:Initialize
	set startDir=%1
	set mask=%2
	set age=%3
	if not defined age ( set age=182 )

:ValidateVars
	rem Check if parameters are missing
	if not defined startDir goto DisplayUsage
	if not defined mask (
		goto DisplayUsage
	) else (
		rem Disallow single wild cards
		if "%mask%"=="*" (
			echo Single wild card character not allowed!
			goto :EOF
		) else (
			if "%mask%"=="*.*" (
				echo Wild card "*.*" not allowed!
				goto :EOF
			)
		)
	)

	rem Ensure age is between 0 and 32768, inclusive.
	if /I %age% LSS 0 (
		echo Number of days is out of range. Range allowed: 0 to 32768.
		goto :EOF
	) else (
		if /I %age% GTR 32768 (
			echo Number of days is out of range. Range allowed: 0 to 32768.
			goto :EOF
		)
	)

	goto RunDeleteOperation

:DisplayUsage
	echo .
	echo DeleteOldFiles.bat by Mario J Vargas (http://angstrey.com/)
	echo Copyright (c) 2009. Mario J Vargas. All rights reserved.
	echo .
	echo Usage:
	echo    deleteoldfiles.bat [starting-directory] [file-mask] [age]
	echo .
	echo       [starting-directory]: Directory path where the delete operation
	echo                             will begin. Files are deleted recursively.
	echo .
	echo       [file-mask]         : The file name pattern to use.
	echo                             Wild cards (*) allowed. A single wild card
	echo                             character is not permitted for security
	echo                             purposes.
	echo .
	echo       [age]               : A number (in days) between 0 and 32768 that
	echo                             specifies the age of the files to delete.
	echo                             The file's last modified date is used.
	echo                             Therefore, any files whose last modified date
	echo                             is less than or equal to the (current date
	echo                             minus [age]) will be deleted.
	echo                             Default value is 182 (approx. 6 months).
	echo .
	echo Examples:
	echo   The following example deletes all files named "ex*.log" that were
	echo   last modified over 1 year (365 days) ago. The starting directory
	echo   is C:\WINDOWS\SYSTEM32\LogFiles:
	echo      deleteoldfiles.bat C:\WINDOWS\SYSTEM32\LogFiles ex*.log 365
	echo .
	echo   The following example searches all subdirectories in C:\Windows
	echo   and deletes all files named "dump.txt" that were last modified
	echo   over 60 days ago:
	echo      deleteoldfiles.bat C:\Windows dump.txt 60
	echo .

	goto :EOF

:RunDeleteOperation
	echo .
	echo ---------- %date% ----------
	echo Starting Directory: %startDir%
	echo Search Mask:        %mask%
	echo File Age:           %age% days old and over
	echo .
	echo .

	choice /T 10 /D Y /M "Start delete operation?"
	if %errorlevel%==1 (
		echo Deleting files...
		rem Delete all files that were last modified over age days ago, starting in startDir
		rem When a file is deleted, report it.
		forfiles /P %startDir% /M %mask% /D -%age% /S /C "cmd /c if @isdir==FALSE ( del /F @path | echo Deleted @path )"
	) else (
		echo Operation canceled.
	)

	echo .
	echo Finished
	echo .
	goto :EOF

19 thoughts on “How to Delete Old IIS Log Files

  1. Hi Mario,

    Awesome little script you’ve wrote. I’ve just used it to clear up a whole bunch of logfiles and it does the job a treat!

    Interesting to learn about the forfiles command too, I think I need to refresh my knowledge of the Windows CommandLine!

    All the best,

    Craig

  2. Hi,

    Thanks a bunch for the script.
    Too bad it doesn’t run on my WIn XP :(
    It runs perfectly on my Win 2K3 though :)

    e.e

  3. Hi Elros,

    Thanks for contacting me. I’m glad the script is working for you. Yes, that’s right. The script is for Windows 2003 Server computers only. The reason is the forfiles command.

  4. Hi Elros,

    That’s good to know. I didn’t try copying those files to my Windows machine. If I had tried that, I would have saved myself a lot of anxiety when I was testing my batch program on my employer’s Windows Server 2003 computer(s). :-)

  5. Hi Mario

    There are lots of folders under the windows\system32\logfiles directory. (some are 2GB) Can i backup these folders adn leave a week of log files or can i only do this in the main directory.

    Cheers

    Will

  6. Hi Mario,

    Thanks for the script; it works great. Is there a way to delete a file on a remote server using a userid and password (possibly network userid and password)?

    Thanks,

    Ebbsa

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>