Purge old files and folders from directory

So at work we have a couple of directories that generate logs on a regular basis. These logs really are not that important. So I keep them for 60 days.

Problem of course is that some also create folders.

So I created this powershell script from some pieces of code I found that will go through the folder and clean out all the old files and then clean out the old folders.

I’m sure I could clean this up a bit, but seeing it does what I want now it’s good enough. You just need to change some of the variables

#Days older than

$HowOld = -60

#Path to the root folder

$Path = "C:\directory you want purged\"

#Deletion files task

get-childitem $Path -recurse | where {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -verbose}

#Deletion empty folders task

do {

$dirs = gci $Path -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName

$dirs | Foreach-Object { Remove-Item $_ }

} while ($dirs.count -gt 0)

Leave a Reply

Your email address will not be published. Required fields are marked *