0
0
PowerShellscripting~5 mins

Log cleanup automation in PowerShell

Choose your learning style9 modes available
Introduction
Cleaning up old log files helps keep your computer tidy and saves space. Automating this task means you don't have to do it by hand.
You want to delete log files older than 30 days to free up disk space.
You have many log files piling up and want to keep only recent ones.
You want to run a cleanup task automatically every week.
You want to avoid manual errors by automating log file removal.
You want to keep your system running smoothly without clutter.
Syntax
PowerShell
Get-ChildItem -Path <folder_path> -Filter <file_pattern> | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-<days>) } | Remove-Item
Replace with the folder where your logs are stored.
Replace with the type of log files, like '*.log'.
Replace with the number of days to keep logs.
Examples
Deletes all .log files in C:\Logs older than 30 days.
PowerShell
Get-ChildItem -Path C:\Logs -Filter *.log | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } | Remove-Item
Deletes all .txt log files older than 7 days in D:\App\Logs.
PowerShell
Get-ChildItem -Path D:\App\Logs -Filter *.txt | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item
Sample Program
This script deletes .log files older than 30 days in C:\Logs by default. You can change the folder and days by passing parameters.
PowerShell
param(
    [string]$LogFolder = "C:\Logs",
    [int]$DaysToKeep = 30
)

Write-Host "Starting log cleanup in folder: $LogFolder"

$oldLogs = Get-ChildItem -Path $LogFolder -Filter *.log | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DaysToKeep) }

if ($oldLogs.Count -eq 0) {
    Write-Host "No log files older than $DaysToKeep days found."
} else {
    foreach ($log in $oldLogs) {
        Write-Host "Deleting: $($log.FullName)"
        Remove-Item $log.FullName
    }
    Write-Host "Cleanup complete. Deleted $($oldLogs.Count) files."
}
OutputSuccess
Important Notes
Always test your cleanup script on a test folder before running on important data.
You can schedule this script to run automatically using Windows Task Scheduler.
Be careful with Remove-Item; it deletes files permanently unless you add safety checks.
Summary
Automate deleting old log files to save space and keep things tidy.
Use Get-ChildItem with filtering by date to find old logs.
Remove-Item deletes the files found by the filter.