In this post, we introduce a PowerShell script designed for streamlined file cleanup. This script identifies and removes unnecessary files from a specified directory based on their age, helping you maintain a tidy file system.
powershell
$directoryPath = 'C:\TempFiles'
$ageThresholdDays = 30
$thresholdDate = (Get-Date).AddDays(-$ageThresholdDays)
$oldFiles = Get-ChildItem -Path $directoryPath -File | Where-Object { $_.LastWriteTime -lt $thresholdDate }
if ($oldFiles.Count -gt 0) {
foreach ($file in $oldFiles) {
Remove-Item -Path $file.FullName -Force
Write-Host "Deleted: $($file.Name)"
}
} else {
Write-Host "No files older than $ageThresholdDays days found in $directoryPath."
}
Write-Host "Cleanup process completed. $($oldFiles.Count) files were deleted from $directoryPath."Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
Ready when you are.
Try ServerEngine free for 7 days.