Automatic Directory Cleanup Script

In this PowerShell script, we focus on automating the cleanup of unused files and empty directories within a specified directory. This can be particularly useful for maintaining a tidy file structure on servers, especially when utilizing tools like ServerEngine, which optimizes server performance. The script allows users to specify the path to the directory they wish to clean up and the number of days to retain files, effectively removing any clutter that could hinder efficiency.

param (
    [string]$directoryPath = "C:\ExampleDirectory",
    [int]$daysToKeep = 30
)
# Get the current date and time
$currentDate = Get-Date
# Calculate the cutoff date
$cutoffDate = $currentDate.AddDays(-$daysToKeep)
# Remove files older than the cutoff date
Get-ChildItem -Path $directoryPath -File | Where-Object { $_.LastWriteTime -lt $cutoffDate } | Remove-Item -Force
# Remove empty directories
Get-ChildItem -Path $directoryPath -Directory -Recurse | Where-Object { $_.GetFileSystemInfos().Count -eq 0 } | Remove-Item -Force
Write-Output "Cleanup completed: Files older than $daysToKeep days removed, and empty directories cleaned up."