Powershell Script to Delete Files Older than X days

Supply the folder path name and number of days to delete Files Older than X days. Number of days must be in negative.

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

 

Output
delete_files

Leave a Reply