Powershell script to clean up files from a specific directory

I came across an issue where the sql backup job that I had scheduled was not cleaning up the old backup files from the backup directory. Although I had specified a file clean up parameter of 1 day but I realized the issue when the backup drive ran out of disk space although I made sure I had provisioned double the space requirement on the drive space.

After investigating the issue I realized that the backup job was not cleaning out the old files from the backup directory. I knew I had to troubleshoot the issue on why the sql job was not cleaning out the old files but I was in the middle of a different production outage and did not have time to work on the cleanup job. And the next scheduled backup was going to start in a couple of hours.

As a quick fix I ran this powershell script to quickly clean out the backup drive so that when the next scheduled backup started – it will be able to run successfully with no issues.

Here is the powershell code I used:

#Parameters
$Path = "B:\Backups" # Path where the file is located
$Days = "1" # Number of days before current date
 
#Calculate Cutoff date
$CutoffDate = (Get-Date).AddDays(-$Days)
 
#Get All Files modified more than the last 30 days
Get-ChildItem -Path $Path -Recurse -File | Where-Object { $_.LastWriteTime -lt $CutoffDate } | Remove-Item –Force -Verbose

The above code will cleanup all files in the specified directory older than 1 day.
You can run this in Powershell ISE on the server itself or save this as a .ps1 file and run it from the powershell command window.

Hope this helps. Good Luck!