Skip to content

Instantly share code, notes, and snippets.

@wincmd64
Last active June 26, 2024 13:26
Show Gist options
  • Save wincmd64/54cf6764bf4d00513138922b47767a08 to your computer and use it in GitHub Desktop.
Save wincmd64/54cf6764bf4d00513138922b47767a08 to your computer and use it in GitHub Desktop.
# Recursively deletes files older than X days (bypassing the Recycle Bin) in specified folder
# by https://t.me/wincmd64
# User variables
$test = 1 # TEST MODE. Set to 0 for real deleting!
$dir = "$env:TEMP" # Folder to search files
$days = 7 # Older than day(s)
$log_file = "$PSScriptRoot\clean.log" # Path to log file
# Logging timestamp
$DT = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $log_file -Value "`r`n[$DT]`r`n"
# Logging files to delete
$count = 1
$filesToDelete = Get-ChildItem -Path $dir -File -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) }
if ($filesToDelete.Count -eq 0) {
Add-Content -Path $log_file -Value "No files found to delete."
} else {
foreach ($file in $filesToDelete) {
if ($test -eq 1) {
# WhatIf mode (simulation)
Add-Content -Path $log_file -Value "$count. $($file.FullName) $($file.LastWriteTime) - WhatIf"
$count++
} else {
# Perform actual deletion
try {
Remove-Item -Path $file.FullName -Force -ErrorAction Stop
Add-Content -Path $log_file -Value "$count. $($file.FullName) $($file.LastWriteTime)"
$count++
} catch {
Add-Content -Path $log_file -Value "Error deleting $($file.FullName): $_"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment