Table of Contents
Delete Files Older Than a Specified Number of Days
In some cases, you want to delete files older than specified number of days. For example, you want to clean up the backup directory to keep only recent backup files.
Simple PowerShell script
To do it, we’ve created a simple PowerShell script to manage and delete files based on their age.
- It offers the option to delete files older than a specified number of days, for example 7 days.
- The script uses the path -Recurse command, commonly referred to as recurse, to delve deep into directories, ensuring it scans all child folders where files are located, be it on a local machine or a shared drive path.
- It does this by comparing the LastWriteTime attribute of each file against the current date. If a file’s age surpasses the set threshold, such as files older than 7 days using specific criteria, it becomes a candidate for deletion.
- You can modify the (Get-Date).AddDays(-X) part of the PowerShell script, where X is the number of days. This allows you to specify the exact number of days you’d like to use as a threshold for deletion.
- You can replace LastWriteTime with CreationTime in the script to filter files based on their creation date instead.
For those who might be dealing with old log files or any content that’s been sitting untouched for the last 30 days, the script is the answer you’re looking for. It provides an efficient way in Windows PowerShell to delete files older than some days, ensuring that only outdated content is removed.
# The location to scan
$location = "D:\Backup"
# Calculate the cutoff date
$cutoffDate = (Get-Date).AddDays(-7)
# Find files older than the specified duration
$oldFiles = Get-ChildItem -Path $location -Recurse -File | Where-Object { $_.LastWriteTime -lt $cutoffDate }
$i = 1
$oldFiles | ForEach-Object {
Write-Progress -PercentComplete ($i/$($oldFiles.Count)*100) -Status "Deleting file: $($_.FullName)" -Activity "Processing: ($i/$($oldFiles.Count))"
Remove-Item $_.FullName -Force
$i++
Start-Sleep -Milliseconds 500
}
You can run the code directly in the PowerShell console or create a PowerShell script for later use.
Tips: By creating a scheduled task in Windows, you can run the PowerShell script at regular intervals to automate the deletion of old files.
As you can see, the old backup files are deleted automatically.
Advanced PowerShell script
Additionally, we can customize the script to delete the old files from any directory and specify any number of dates for deletion. When running the script:
- It will ask you to enter the path of the directory that you want to delete the old files from.
- Prompt you to enter the any number of dates for deletion.
- Confirm the deletion: 1 for delete, 2 for do nothing.
# Prompt user for the location to scan
$location = Read-Host "Enter the location to scan for files and folders"
$location = ($location).trim('"')
$location = ($location).trim("'")
# Prompt user for the duration (older than how many days)
$days = Read-Host "Enter the duration (older than how many days)"
# Prompt user for the action (1 for delete, 2 for do nothing)
$action = Read-Host "Enter the action (1 for delete, 2 for do nothing)"
# Calculate the cutoff date
$cutoffDate = (Get-Date).AddDays(-$days)
# Find files older than the specified duration
$oldFiles = Get-ChildItem -Path $location -Recurse -File | Where-Object { $_.LastWriteTime -lt $cutoffDate }
# Find folders older than the specified duration
$oldFolders = Get-ChildItem -Path $location -Recurse -Directory | Where-Object { $_.LastWriteTime -lt $cutoffDate }
# Take action based on user's choice
if ($action -eq "1") {
$i = 1
$oldFiles | ForEach-Object {
Write-Progress -PercentComplete ($i/$($oldFiles.Count)*100) -Status "Deleting file: $($_.FullName)" -Activity "Processing: ($i/$($oldFiles.Count))"
Remove-Item $_.FullName -Force
$i++
Start-Sleep -Milliseconds 500
}
} elseif ($action -eq "2") {
Write-Host "No action taken. There are $($oldFiles.Count) files older than $days days" -ForegroundColor Yellow
} else {
Write-Host "Invalid action selected." -ForegroundColor Yellow
}
The output when running the script on our computer.
Not a reader? Watch this related video tutorial: