Hey there! Need to regularly clean up old files in a directory? Here's a quick guide using a PowerShell script.
🛠️ The Script (delete_old_files.ps1):
param (
[string]$path
)
$ThirtyDaysAgo = (Get-Date).AddDays(-30)
$logFileName = "log_delete_"+(Get-Date -Format "yyyyMMddHHmmss") + ".txt"
$logPath = Join-Path $PSScriptRoot $logFileName
function WriteToLog($message) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $logPath -Value "[$timestamp] $message"
}
Get-ChildItem -Path $path -Recurse -File | Where-Object { $_.LastWriteTime -lt $ThirtyDaysAgo } | ForEach-Object {
try {
Remove-Item $_.FullName -Force
$msg = "Deleted $($_.FullName)"
Write-Output $msg
WriteToLog $msg
} catch {
$errMsg = "Failed to delete $($_.FullName): $_"
Write-Error $errMsg
WriteToLog $errMsg
}
}
This script also writes a log file so that you never have to worry about what it might or might not delete.
🚀 How to Run:
- Save the script to delete_old_files.ps1.
- Open PowerShell (Run as Admin for best results).
- Navigate to the script's directory.
- Run:
.\delete_old_files.ps1 -path "C:\path\to\your\directory"
📅 Schedule it with Windows Task Scheduler:
- Open Task Scheduler.
- Create a new basic task.
- Set it to run daily or as you wish.
- Action: Start a program > powershell.
- Arguments:
-ExecutionPolicy Bypass -File "C:\path\to\delete_old_files.ps1" -path "C:\your\target\directory"
Done! 🎉 Your directory will now stay clean from files older than 30 days.
Remember: Always backup important files before running deletion scripts. Happy coding! 🚀
Top comments (0)