Wednesday, August 13, 2014

Powershell: Script to purge old files from a folder

So I need to backup the SQL DB of a mission critical app.  The app sits on a virtual machine and backups need to get written to a NAS device.  But if there is a network or NAS issue then the backups won't get written, so no current backups.  What I do in this scenario is write the backups locally first, to c:\DB_backups, then script a task to sync the backup directory to the NAS.  If I have daily backups then the NAS will store all of the daily rolling backups, but that will eat up space on the C drive, which is bad.  So I need to purge the DB_backups folder, there are a few ways to do this and the easiest I found is to use powershell:
 Get-ChildItem 'C:\DB_Backup' -Recurse | Where {$_.creationtime -lt (Get-Date).AddDays(-10)} | Remove-Item  
This is pretty clever on powershell's part, lets step through what it does.
Get-ChildItem 'C:\DB_Backup' -Recurse
What this does is list all of the items in this folder as objects, and I am recursing through all of the folders in this folder, but that is not necessarily needed for this job.
Where {$_.creationtime -lt (Get-Date).AddDays(-10)}
The objects in this folder is then piped to this line.  Where is an alias for Where-Object.  We are using where because we only want to select files with specific attributes from this directory.  These attributes are defined by the $_.creationtime.  The creation time is then compared to today's date (Get-Date) using -lt (less than).  But we only want the files older than 10 days ago, so we subtract 10 from Get-Date, using the AddDays modifier.  So now we are listing all of the files older than 10 days, pretty neat, now to delete them.
The cmd way of doing things is using del, which is actually an alias for -Remove-Item, neat.  This will remove the 10 day old objects we piped to it in the previous line.

Save it all as a .ps1 file and schedule the job in task scheduler to run daily to keep your C drive to size.