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.
- Detects if IIS (Web-Server role) is installed.
- Imports the WebAdministration module.
- Iterates all IIS websites and targets each site’s log directory (e.g.,
%SystemDrive%\inetpub\logs\LogFiles\W3SVC{SiteID}). - Deletes
.logfiles older than N days (configurable). - Shows real‑time progress bars (overall and per-site).
- Writes detailed entries to the Application log with source “IIS Log Cleanup Script”.
- Prints a summary table with WebsiteName, WebsiteID, and DeletedCount.
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 = 49500Tip: Choose an
EventIDthat doesn’t clash with other monitoring rules in your environment.
- Windows Server with IIS (Web-Server) role installed (or the script exits gracefully).
- PowerShell (runs with built-in cmdlets; uses
WebAdministration). - Run as Administrator:
- Required to create the Application log source (first run):
New-EventLog -LogName Application -Source "IIS Log Cleanup Script" - Required to access IIS configuration and write to protected directories.
- Required to create the Application log source (first run):
- File system access to IIS log paths for each site.
- Launch Windows PowerShell as Administrator.
- Navigate to the script directory:
cd C:\Path\To\Script
- Execute:
.\IISLogCleanUp_WithLogging.ps1
On completion, you’ll see a table similar to:
WebsiteName 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.
Examples of messages you’ll see:
- “Removing Old IIS Log Files”
- “Checking IIS Is Installed”
- “IIS Is Installed”
- “Import WebAdministration Module”
- “WebAdministration Module Imported Succesfuly”
- “Checking logs for {SiteName} (ID: {SiteID})”
- “Removed {N} logs for {SiteName} (ID: {SiteID})”
- “Finished Removing Old IIS Log Files”
The script creates the event source if it doesn’t exist:
New-EventLog -LogName Application -Source "IIS Log Cleanup Script" -ErrorAction SilentlyContinue
For each IIS website, files matching *.log in the site’s log directory are deleted only if:
- The directory exists, and
LastWriteTimeis older than(Get-Date).AddDays(-$logfileMaxAge)
No other files are touched.
Automate cleanup with a daily task:
- Open Task Scheduler → Create Task…
- General:
- Name:
IIS Log Cleanup - Run whether user is logged on or not
- Run with highest privileges
- Name:
- Triggers:
- New → Daily → Time that suits off-hours (e.g., 02:00)
- Actions:
- Program/script:
powershell.exe - Add arguments:
-NoProfile -ExecutionPolicy Bypass -File "C:\Path\To\IISLogCleanUp_WithLogging.ps1"
- Program/script:
- Conditions:
- (Optional) Uncheck “Start the task only if the computer is on AC power” on servers.
- Settings:
- Allow task to be run on demand
- Stop the task if it runs longer than: 2 hours (optional)
- 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
$logfileMaxAgeon a test server to confirm behavior. - Consider setting NTFS permissions on log directories appropriately for the service account running the task.
Get-Websitenot found / module import fails
Ensure the IIS Management scripts feature is installed and theWebAdministrationmodule is available:- Server Manager → Web Server (IIS) → Management Tools → IIS Management Scripts and Tools
- Or via PowerShell:
Get-WindowsFeature Web-Scripting-Tools
- 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.
The script returns an array of objects you can capture or pipe:
$results = .\IISLogCleanUp_WithLogging.ps1
$results | Format-Table
$results | Export-Csv .\IISLogCleanupResults.csv -NoTypeInformationObject shape:
WebsiteName | WebsiteID | DeletedCount
- 1.0 – 2019-07-12
Initial version: retention-based cleanup, progress bars, Application log entries, per-site summary.
- Add parameters (
[CmdletBinding()]) to allow:-LogfileMaxAge-EventId-IncludeSite/-ExcludeSite-WhatIfand-Verbosesupport
- 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.
/YourFolder
├── IISLogCleanUp_WithLogging.ps1
└── README.md ← (this file)