How to Automate IIS Log Clean Up



Last updated: January 28th, 2024

Problem

Recently, a user posted me a message that the photo they tried uploading was not going through. I tried recreating the issue on the site and wasn't able to. I was somewhat confused when yet another user mentioned not being able to upload a photo. I was not able to recreate the issue locally.
When I logged onto the server I noticed that the disk drive was full. From here I assumed that file uploads went to a temporary location before being sent to a CDN. What had happened was the IIS logs had consumed all the disk space. The solution was to delete the logs and some other files. Of course, this was a manual job.
IIS logs each request and those logs are not useful in my case so I can get rid of them every 30 days if I want. I needed to find a way to automate the task of disposing old log files so that users continued to get great service.

Solution

The solution to the old log file problem is to schedule a task which runs a script that deletes old files. In my case I want all the sites to be cleaned every day and I don't want to update the script for new sites that get added or removed. My goal is to have a script that will delete all the log files older than 30 days for every site that I have and will add to this server.
First make the file, in this case: C:\scripts\cleanLogs.ps1
The contents of the script are:

Scheduling The Script To Run

To get the script to run every day to wipe out the logs over the time threshold, type: taskschd.msc into PowerShell. From there you can click: Create Basic Task to Start a program, go through the steps to locate your script and have it run each day. Essentially you are starting a program (powershell.exe) and as arguments to it, passing: -File "YOUR_SCRIPT_PATH\YOUR_SCRIPT_NAME.ps1". After you set this up with a daily trigger, you are set. You can click your task in the list and run it to see it execute before the time when it will run automatically.
For more details and a walk through, check this tutorial.

Inspiration

My solution is an adaptation of two other posts I read. The first is about scheduling tasks on Windows. The second is on deleting IIS log files however, I had to adapt it to get all my sites by name and restructure the file paths to my virtual directories.

Comments

No Comments

Post Comment

Prove you are human 9 + 11 =

Tagged: IIS


Join my email list!



ryan
About Me

With 15 years in tech, I've excelled as a senior software engineer, specializing in ASP.NET, C#, SQL, Azure, and front-end technologies. I've led diverse projects across various sectors, from startups to global corporations, particularly during my decade in the San Francisco Bay Area.


Sign Up With SoftSys Hosting! (My host)