Delete Files and Folders Older Than X Days

Often times admin have to creates tasks like removing log files or some other files on a regular schedule. Here is an automated way of removing files / folders older than X days.

Create a Batch file or Powershell script and add it to scheduled task.

[su_tooltip position=”north” content=”Here’s what all of those funky switches do. The first two arguments are for the InstallShield application, setup.exe. /S requests a silent installer, and /v lets the application know that you’re going to pass switches directly to the MSI. This is why the command structure after the /v is enclosed in double quotes. The /qn portion is MSI-speak for no user interface, while the REBOOT=R portion is toReallySupress the reboot. ADDLOCAL is describing what features to install locally, while REMOVE states to toss out the HGFS (Shared Folders) feature. This way ensures that new features will be added without having to call them all out in a list.”]Please check permissions on the files and folders. If you have unique or specialized permission on the file or folders these wont work.[/su_tooltip]

Batch File:

@echo off
:: set folder path
set dump_path=c:\shares\dump

:: set min age of files and folders to delete
set max_days=7

:: remove files from %dump_path%
forfiles -p %dump_path% -m *.* -d -%max_days% -c "cmd  /c del /q @path"

:: remove sub directories from %dump_path%
forfiles -p %dump_path% -d -%max_days% -c "cmd /c IF @isdir == TRUE rd /S /Q @path"

Powershell:

# set folder path
$dump_path = "C:\shares\dump"

# set min age of files
$max_days = "-7"
 
# get the current date
$curr_date = Get-Date

# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)

# delete the files
Get-ChildItem $dump_path -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item