Table of Contents
Automatically Clean Up Old Log Files with PowerShell
If you’re managing a web server or any system that generates log files, you’ll quickly notice that these files can grow very large over time. This article will show you how to automatically delete old log files using PowerShell, so you don’t have to manually clean them up.
Why Clean Up Log Files?
Log files are important for tracking system activity, but they can take up a lot of disk space. If you don’t clean them regularly, your server might run out of storage space. This script will automatically remove log files that are older than 30 days.
Prerequisites
Before you start, make sure you have:
- A Windows server with PowerShell installed
- Administrative rights to run PowerShell scripts
- The folder path where your logs are stored (usually C:\inetpub\logs\LogFiles)
The PowerShell Script
Here’s a simple script that will automatically clean up old log files:
# Define the folder path where logs are stored
$LogFolder = "C:\inetpub\logs\LogFiles"
# Define how many days old files should be deleted (30 days)
$DaysOld = 30
# Define the folder where log files will be saved
$ScriptLogFolder = "C:\inetpub\logs\LogFiles\ScriptLogs"
# Create the log folder if it doesn't exist
if (!(Test-Path $ScriptLogFolder)) {
New-Item -Path $ScriptLogFolder -ItemType Directory -Force
}
# Create today's log file name
$LogFile = "$ScriptLogFolder\logcleanup_$(Get-Date -Format 'yyyyMMdd').log"
# Function to write log messages
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
Write-Host $logEntry
Add-Content -Path $LogFile -Value $logEntry -ErrorAction SilentlyContinue
}
try {
Write-Log "Starting log cleanup process..." "INFO"
# Check if the main log folder exists
if (Test-Path $LogFolder) {
# Find all files older than 30 days
$OldFiles = Get-ChildItem -Path $LogFolder -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { (Get-Date) - $_.CreationTime -gt (New-TimeSpan -Days $DaysOld) }
if ($OldFiles.Count -gt 0) {
Write-Log "Found $([int]$OldFiles.Count) old files to delete" "INFO"
$DeletedCount = 0
$ErrorCount = 0
foreach ($File in $OldFiles) {
try {
Remove-Item $File.FullName -Force -ErrorAction Stop
Write-Log "Deleted: $($File.FullName)" "INFO"
$DeletedCount++
}
catch {
Write-Log "Error deleting $($File.FullName): $($_.Exception.Message)" "ERROR"
$ErrorCount++
}
}
Write-Log "Cleanup complete: Deleted $DeletedCount files, $ErrorCount errors" "INFO"
}
else {
Write-Log "No old files found to delete" "INFO"
}
}
else {
Write-Log "Log folder does not exist: $LogFolder" "ERROR"
}
# Delete old log files (older than 30 days)
$Today = Get-Date
$OldLogFiles = Get-ChildItem -Path $ScriptLogFolder -File -ErrorAction SilentlyContinue |
Where-Object { ($Today - $_.CreationTime).Days -gt 30 }
if ($OldLogFiles.Count -gt 0) {
Write-Log "Deleting old log files (older than 30 days): $($OldLogFiles.Count) files" "INFO"
$OldLogFiles | ForEach-Object {
try {
Remove-Item $_.FullName -Force -ErrorAction Stop
Write-Log "Deleted log file: $($_.FullName)" "INFO"
}
catch {
Write-Log "Error deleting log file $($_.FullName): $($_.Exception.Message)" "ERROR"
}
}
}
Write-Log "Log cleanup process completed!" "INFO"
}
catch {
Write-Log "Unexpected error: $($_.Exception.Message)" "ERROR"
}How to Use This Script
- Save the Script
- Open Notepad or any text editor
- Copy and paste the script above
- Save the file with a .ps1 extension (for example: CleanLogs.ps1)
- Run the Script Manually
- Open PowerShell as Administrator
- Navigate to the folder where you saved the script
- Run: .\CleanLogs.ps1
- Set Up Automatic Execution
- Open Task Scheduler
- Click Create Basic Task
- Give it a name like Clean Log Files
- Set the trigger to run daily at your preferred time
- For the action, choose Start a program
- Program/script: PowerShell.exe
- Add arguments: -ExecutionPolicy Bypass -File “C:\Path\To\Your\CleanLogs.ps1”
- Set the start folder to C:\ or leave it blank
What This Script Does
- Finds old files: Looks for log files older than 30 days
- Deletes them automatically: Removes the old files without asking
- Creates logs: Saves what happened in a log file for later review
- Cleans up old logs: Also removes old log files from the script itself (keeping only 30 days)
Important Notes:
- Test first: Always test the script manually before setting it up automatically
- Backup important logs: Make sure you don’t need any old log files for troubleshooting
- Run as Administrator: The script needs administrator rights to delete files
- Check permissions: Make sure the user running the task has permission to delete files in the log folders
Troubleshooting Tips
If the script doesn’t work when scheduled:
- Check that you’re running it as Administrator
- Make sure the path to the script is correct
- Verify that the execution policy allows PowerShell scripts
- Try running PowerShell with -ExecutionPolicy Bypass manually first
Conclusion
This simple PowerShell script helps you automatically manage your server’s disk space by cleaning up old log files. It’s perfect for beginners who want to keep their servers running smoothly without manual intervention. The script is safe, simple, and very effective at keeping your log directories clean.
Remember to test it first and always keep a backup of important logs before running automated cleanup scripts!
