Delete files older than a number of days using Powershell

I was recently tasked with automating a process of removing log files from a directory that were older than a specified number of days, where the application generating the log files has no retention policy management.

In this example files older than seven days were required to be removed.

The retention script (and like most scripts I write) will be compiled in Powershell and for flexibility and will require the log folder and number of days to retain the file to be specified as a variable.

Once the variables were configured, the log folder specified (in the below example, C:\Program Files\Application\Log) is then recurse to obtain all items and then filtered to include only items where the last modified time was less than the number of days specified in the retain variable, in this case seven.

Once the files have been filtered according to the last modified date, the files will be deleted using the force parameter to allow items to be removed, that otherwise could not be changed.

# Specify the directory to remove log files.
$LogFolder = “C:\Program Files\Application\Log”

#Specify the number of days to retain log files.
$Retain = “7”

# Removes log files in the specified log folder directory according to the number of days specified to retain the log files.

Get-ChildItem $LogFolder -recurse | where {$_.Lastwritetime -lt (date).adddays(-$Retain)} | Remove-Item -Force

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s