Navigation

Script to delete folder older than 30 days… by Name

I had a need, on one of my file servers, to delete some data that was older than 30 days, to clear space. This would need to be a re-occurring task, so what better way to accomplish it than to script it!

Here’s the rub… The folders are each in a YYYYMMDD format (ex: 20170115), yet the content in the folders could be dated other than the folder name itself. For instance, there could be a folder (say 20170626) that is in the future, so we don’t want to delete it, even though the files in the folder could be from a date in the past. And to add complexity, the folders to be deleted were on a MOUNT POINT inside another drive.

I needed to find the folder to delete based on the folder name and not the item date. Also, the data on this file server is also backed up to one of our Isilon storage arrays, as the amount of data is too big for our backup targets to normally handle. Before we delete the folder for 30+ days ago, we want to make sure all the data has been duplicated on the Isilon. We have a script that runs nightly to do this, but in order to make sure the data is 100% up to date on the Isilon, I decided to incorporate a robocopy command in the script. Also, the Isilon storage only allowed specific accounts access, so I had to map a drive first.

I used variables to set the path that the data was located, as well as the destination for the backup on the Isilon. I also included a variable for the robocopy LOG so I could put the date into the log file name, so there was a new log each day.

Once it gathered the folder name to delete, it runs the robocopy, and once complete, deletes the folder and all it’s subfolders/files. As this is a file server cluster and I run the script via task scheduler on both nodes, I included an IF statement to check to see if the drive exists before proceeding. At the end, it sends an email and includes the before & after free space.