Here’s an extremely simple PowerShell script to remove old files based on age. You could use it to enforce a policy that keeps 90 days of ETL input files on a server. Files older than that would purged with this script. The script would be invoked by a SQLAgent CMDExec task or a Windows Task Scheduler job. Be sure to test with the -whatif switch before deploying.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $intFileAge = 15 #age of files in days $strCleanupPath = "filesystem::\\Server\Share..." #path to clean up - UNC paths permissible and probably preferred #create filter to exclude files newer than specified age as well as all folder objects Filter Select-FileAge { param($days) If ($_.PSisContainer) {} # Exclude folders from result set ElseIf ($_.LastWriteTime -lt (Get-Date).AddDays($days * -1)) {$_} } get-Childitem -recurse $strCleanupPath | Select-FileAge $intFileAge | remove-item |
Nice and concise. Helped with a cleanup task I had.
Great post… Could be used as a script using parameters real easy.
Thanks for the simple and helpful script.