Script: IISLogCleanUp_WithLogging.ps1
Author: Andrew Samuel
Created: 2019-07-12
Purpose: Automatically remove IIS log files older than a configured retention period, show progress during execution, and write operational events to Windows Event Viewer → Application under a configurable Event ID. Outputs a summary table of deletions per IIS site.
%SystemDrive%\inetpub\logs\LogFiles\W3SVC{SiteID})..log files older than N days (configurable).Open the script and adjust the variables in “Set Custom Variables”:
# Maximum age of log files in days to keep
$logfileMaxAge = 28
# Event ID to log events under
$eventId = 49500
Tip: Choose an EventID that doesn’t clash with other monitoring rules in your environment.
WebAdministration).New-EventLog -LogName Application -Source "IIS Log Cleanup Script" cd C:\Path\To\Script .\IISLogCleanUp_WithLogging.ps1WebsiteName WebsiteID DeletedCount
----------- --------- ------------
Default Web Site 1 42
API 2 17
Portal 3 0
The script logs to Windows Event Viewer → Application using the source “IIS Log Cleanup Script” and your configured EventID.
The script creates the event source if it doesn’t exist:
text> New-EventLog -LogName Application -Source "IIS Log Cleanup Script" -ErrorAction SilentlyContinue > ``` --- ## 📁 What gets deleted? For each IIS website, files matching `*.log` in the site’s log directory are deleted **only if**: - The directory exists, and - `LastWriteTime` is **older than** `(Get-Date).AddDays(-$logfileMaxAge)` No other files are touched. --- ## 🕒 Scheduling (Task Scheduler) Automate cleanup with a daily task: 1. Open **Task Scheduler** → **Create Task…** 2. **General**: - Name: `IIS Log Cleanup` - Run whether user is logged on or not - **Run with highest privileges** 3. **Triggers**: - New → Daily → Time that suits off-hours (e.g., 02:00) 4. **Actions**: - Program/script: `powershell.exe` - Add arguments:
-NoProfile -ExecutionPolicy Bypass -File "C:\Path\To\IISLogCleanUp_WithLogging.ps1"
5. **Conditions**:
- (Optional) Uncheck “Start the task only if the computer is on AC power” on servers.
6. **Settings**:
- Allow task to be run on demand
- Stop the task if it runs longer than: 2 hours (optional)
---
## 🔐 Permissions & Safety
- **Run as Admin** is recommended/required for:
- Event log source creation (first run)
- Accessing IIS config, log directories, and site list
- Test on **non-production** first, or reduce `$logfileMaxAge` on a test server to confirm behavior.
- Consider setting NTFS permissions on log directories appropriately for the service account running the task.
---
## 🛠 Troubleshooting
- **`Get-Website` not found / module import fails**
Ensure the IIS Management scripts feature is installed and the `WebAdministration` module is available:
- Server Manager → **Web Server (IIS)** → **Management Tools** → **IIS Management Scripts and Tools**
- Or via PowerShell:powershell- **No progress bars in scheduled run**
Task Scheduler runs non-interactively; progress bars won’t render. Use **Event Viewer** and task **History** for auditing.
- **Access denied deleting logs**
Verify the task’s run-as account has **Modify/Write** on the IIS log directories (usually `%SystemDrive%\inetpub\logs\LogFiles\`).
- **Event source creation error**
Run the script once interactively as Administrator to initialize the source.
---
## 🔄 Output
The script returns an array of objects you can capture or pipe:powershellObject shape:text---
## 📦 Version History
- **1.0 – 2019-07-12**
Initial version: retention-based cleanup, progress bars, Application log entries, per-site summary.
---
## 🧭 Notes & Future Enhancements (optional)
- Add **parameters** (`[CmdletBinding()]`) to allow:
- `-LogfileMaxAge`
- `-EventId`
- `-IncludeSite` / `-ExcludeSite`
- `-WhatIf` and `-Verbose` support
- Export summary to **CSV** or **JSON** automatically with a `-ReportPath`.
- Add **structured event IDs** for start, per-site, and end states to simplify SIEM parsing.
---
## 🧩 File Layout