Powershell : Script to delete files older than N days

I recently setup a job to backup transaction logs for live databases every 15 mins. To prevent these files filling up the drive, I needed to to write a script to delete old log files so that it can be automated.

Here is the Powershell script I have written to delete files older than 5 days. The no of days and the path are parameters, so the values can be changed as required.


This then needed to be added as a scheduled task in windows scheduler. When a Powershell script needs to be scheduled, in the action window write Powershell.exe in program and specify the script file name with path in the argument text box as below.


Here is the text from Powershell script for anyone to copy and paste.

## This deletes files older than 7 days
## You can alter the parameter values to change the path and no of days
$Path = "I:\TransactionLogBackup\UK_NAV"
$days = -7
Get-ChildItem -path $Path | where {$_.Lastwritetime -lt (date).adddays($days)} | remove-item

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s