PowerShell script to delete files older than x days

Powershell Script to Delete Files Older than X days

Files and folders can accumulate over time and take up considerable space in the database or hard drives and end up slowing the computer considerably. However, deleting them manually isn't quite scalable. This is where PowerShell scripts can be of help. Execute the following script to delete all files older than a certain number of days, in a go.

Powershell script to delete files older than x days

Simply provide the folder pathname and the number of days from which the files have to be deleted. It is to be noted that the number of days must be negative. The following PowerShell script deletes files older than some days. You can use it to clean up old log files or temp folders. This example will use PowerShell to delete files older than 5 days.

Script
<#
.SYNOPSIS
This script can be used to delete files older than X days.
.DESCRIPTION
This script can be used to delete files older than X days.
.EXAMPLE
C:\PS> C:\Script\Delete_Files_x_Days_older.ps1 C:\Users\gautam-2374\Desktop\testfolder -5
Delete files older than 5 days.
#>

param ( [string]$file_path, [int]$max_days )
#Fetches the current date.

$curr_date = Get-Date
#Fetches the date before which files created need to be deleted.

$del_date = $curr_date.AddDays($max_days)
#Recursively delete the files in specified path.

Get-ChildItem $file_path -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item