Quick (and simple) Tip: Deleting old files

Got a log directory that gets stuffed with files? Want a quick and simple way to clean out old files? Here is a simple code snippet. It will scan one directory and remove any file more than 30 days old.

<cfset logdir = "/Applications/ColdFusion8/logs">

<cfdirectory action="list" directory="#logdir#" name="files" type="file">

<cfset thirtydaysago = dateAdd("d", -30, now())>

<!--- get older files ---> <cfquery name="oldfiles" dbtype="query"> select name from files where datelastmodified < <cfqueryparam cfsqltype="cf_sql_timestamp" value="#thirtydaysago#"> </cfquery>

<cfoutput>Out of #files.recordCount# files, there are #oldfiles.recordCount# to delete.</cfoutput>

<cfif oldfiles.recordCount> <cfloop query="oldfiles"> <cffile action="delete" file="#logdir#/#name#"> </cfloop> </cfif>

Not much going on here. I'll point out the type="file" attribute to cfdirectory. This was added in ColdFusion 8. It tells the tag to only return files, not subdirectories. Outside of that the code just uses query of query to gather files of a certain age (I won't say old, let's be polite) and it then loops over them to delete them.

In my next post I'll show an alternative - archiving to a zip.

Edit: I had my < and > messed up above. It is right now.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com