0
0
PowerShellscripting~30 mins

Log cleanup automation in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
Log cleanup automation
📖 Scenario: You are managing a server that generates many log files daily. To save disk space, you want to automatically delete old log files that are no longer needed.
🎯 Goal: Create a PowerShell script that deletes log files older than a certain number of days from a specific folder.
📋 What You'll Learn
Create a variable with a list of log files in a folder
Create a variable for the age limit in days
Use a loop to find and delete files older than the age limit
Print the names of deleted files
💡 Why This Matters
🌍 Real World
Automating log cleanup helps keep servers running smoothly by freeing disk space and reducing manual work.
💼 Career
System administrators and DevOps engineers often write scripts like this to maintain healthy server environments.
Progress0 / 4 steps
1
Get the list of log files
Create a variable called logFiles that stores all files with the extension .log from the folder C:\Logs using Get-ChildItem.
PowerShell
Need a hint?

Use Get-ChildItem with -Path and -Filter to get log files.

2
Set the age limit for deletion
Create a variable called daysLimit and set it to 30 to represent the number of days after which log files should be deleted.
PowerShell
Need a hint?

Just assign the number 30 to daysLimit.

3
Delete old log files
Use a foreach loop with the variable file to go through logFiles. Inside the loop, check if file.LastWriteTime is older than (Get-Date).AddDays(-daysLimit). If yes, delete the file using Remove-Item.
PowerShell
Need a hint?

Use foreach to loop. Use if to compare dates. Use Remove-Item to delete.

4
Print deleted file names
Modify the loop to print the name of each deleted file using Write-Output right after deleting it. Use $file.Name to get the file name.
PowerShell
Need a hint?

Use Write-Output to print the deleted file name inside the if block.