🚀 GitHub Showcase

IIS-Clean-Up

Last commit date badge Open issues count badge Repository size badge Latest release version badge
View on GitHub
Languages
PowerShell 100.0%

📖 README

IIS Log Cleanup with Event Logging

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.


📊 Status & Info

Last Commit
Issues
Repo Size


✨ What the script does

  • 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 .log files 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.

⚙️ Configuration

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.

✅ Prerequisites

  • 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.
  • File system access to IIS log paths for each site.

▶️ How to run

  1. Launch Windows PowerShell as Administrator.
  2. Navigate to the script directory:
       cd C:\Path\To\Script
  3. 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

🧾 Event Logging

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
> ```

---

## 📁 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:
text

-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
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.

---

## 🔄 Output

The script returns an array of objects you can capture or pipe:
powershell
$results = .\IISLogCleanUp_WithLogging.ps1
$results | Format-Table
$results | Export-Csv .\IISLogCleanupResults.csv -NoTypeInformation
Object shape:
text
WebsiteName | WebsiteID | DeletedCount
---

## 📦 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

/YourFolder
├── IISLogCleanUp_WithLogging.ps1
└── README.md ← (this file)
```

🚀 Releases

No releases available for this repository.