Last active
June 26, 2024 13:26
-
-
Save wincmd64/54cf6764bf4d00513138922b47767a08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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