Monday, November 23, 2015

PowerShell Script to cleanup Old Files / Folders

# Function that deletes any files, recursively, from a directory that are older than X days for modified day.
# this is mostly stolen from http://stackoverflow.com/a/19326146/18524
function Cleanup-Dir
{
param([string]$path, [int]$limit)
$minDay = (Get-Date).AddDays(-1 * $limit)
# delete files older than $limit
Get-ChildItem -Path $path -Recurse -Force `
| Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $minDay } `
| Remove-Item -Force -ErrorAction SilentlyContinue
# delete any empty directories left behind after deleting old files
Get-ChildItem -Path $path -Recurse -Force `
| Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } `
| Remove-Item -Force -ErrorAction SilentlyContinue
}
#now, run this cleanup function on ...
Cleanup-Dir "C:\temp" 30
Cleanup-Dir "C:\Users\*\Backup" 14 # powershell can do fancy stuff with regex and wildcards

1 comment:

Unknown said...

It may come in handy to me. But you need to be careful with such cleanup files. Suddenly you may lose important runing files. Once it was necessary to to search among a lot of sources, where it possible to have access for api-ms-win-crt-runtime-l1-1-0.dll download https://fix4dll.com/apimswincrtruntimel110_dll as a result, I found this source. Now I use it if I have errors with opening applications. But not often, because I have already restored all the missing files.

Disqus for A Nofsinger's Blog