Home » PowerShell Scripts » PowerShell Script to Delete Files Older Than X Days

PowerShell Script to Delete Files Older Than X Days

If you have a folder that constantly fills up, deleting old files not only restores valuable disk space but also makes managing the folder easier. While you can manually scan the directory and remove old files, you can make your life much easier with the magic of PowerShell automation. By running the script below, you can automatically delete all the files older than a specified number of days, 90 days for example.

I made this script inspired by Windows’ Storage Sense feature which automatically deletes older files from the Recycle Bin and Downloads folder. While Storage Sense is limited to these two folders, my script allows you to specify any directory and the number of days to wait before deleting a file.

So, without further ado, let me introduce you to the PowerShell script to delete files older than X days and show you how to run it manually & on schedule.

PowerShell Script to Auto Delete Files Older Than X Days

<#
  Script Name: Delete Old Files
  Description: This script forcefully deletes files not modified in a user-specified number of days. 90 Days, by default.
  Author: Bashkarla Vamsi
  URL: https://windowsloop.com
#>

# Set the directory path directly in the script
$folderPath = ""  # Add folder path between quotes. For example: "C:\Users\YourUsername\Documents\TargetFolder"

# Set the number of days to wait before deleting a file
$days = 90  # Change this value if necessary. Default = 90

# Check if the folderPath variable is set
if ($folderPath -eq "") {
   Write-Host "Error: The folder path is not set. Please edit the script and set the `$folderPath` variable to the directory you wish to clean."
   exit 1  # Exit with error code 1 when no path is set
} elseif (Test-Path $folderPath) {
   # Get today's date
   $currentDate = Get-Date

   # Calculate the date limit based on user-specified days
   $dateLimit = $currentDate.AddDays(-$days)

   # Get all the files in the folder
   $files = Get-ChildItem -Path $folderPath -File

   # Loop through each file
   foreach ($file in $files) {
       # Check if the file's last modified time is older than the specified number of days
       if ($file.LastWriteTime -lt $dateLimit) {
           # Delete the file forcefully
           Remove-Item $file.FullName -Force
           Write-Host "Deleted: $($file.FullName)"
       }
   }
   Write-Host "Cleanup complete."
   exit 0
} else {
   Write-Host "Error: The folder path '$folderPath' does not exist or is not accessible. Please verify the path and ensure it is correct. Edit the script to update the path if necessary."
   exit 1  # Exit with error code 1 when the path does not exist
}

Here’s a quick rundown of how the script works and how you can customize it to fit your needs:

Script Customization

Directory Path ($folderPath): This is where you specify the folder path from which you want to delete old files. Simply replace the dummy path C:\Users\YourUsername\Documents\TargetFolder with the actual path. Make sure to enter the path between quotes.

Number of Days ($days): This variable determines how old the files need to be before they are deleted. By default, this variable is set to 90. That means, the script deletes files older than 90 days. You can change this value to any number that suits you. For example, to wait 120 days before deleting files, simply change 90 to 120.

Explanation: How Does the Script Work?

First, the script checks if the specified folder exists. If it exists, it then gets today’s date with the Get-Date cmdlet and subtracts the number of user-specified days to find the date limit.

Next, it lists all the files in the specified folder using the Get-ChildItem cmdlet, and for each file, if the last modified date is earlier than the date limit, it deletes the file using the Remove-Item cmdlet.

If you did not enter a folder path or if the folder does not exist, the script stops execution and shows the error message using the Write-Host cmdlet.

Steps To Run the PowerShell Script

Before You Begin (Caution)

  • The script will delete the files permanently (i.e., it will skip the recycle bin) and there is no undo option. So, be careful.
  • Always test the script on a test or non-critical folder first. Once you verify that it runs according to your expectations, only then use it on the actual folder.
  • If the files are important, make that they are backed up regularly.

Steps

Follow these steps to run the script to delete files older than a specified number of days in a folder:

Save the script

1. Open Notepad from the Start menu.

open notepad using the start menu

2. Copy the above script and paste it into Notepad.

3. Modify the $folderPath variable to add the folder path between quotes.

4. Optionally, modify the $days variable to change how old the files should be before they are deleted. The default is 90 days.

add folder path in the PowerShell script

5. Select File > Save.

save PowerShell script

6. Go to a folder where you want to save the file.

7. Enter DeleteOldFiles.ps1 in the “File Name” field.

8. Select All Files from the “File Type” dropdown menu.

9. Click Save.

set PowerShell script file name and click save

Note: You can also download the script from my GitHub page, open it with Notepad, change the “$folderPath” and “$days” variables as you need, and save it.

Run the Script

To run the script, follow the below steps:

1. Press the Start button.

2. Search for Windows PowerShell and click Run as Administrator.

open PowerShell as admin

3. Run the following command to temporarily change the execution policy to unrestricted.

Set-ExecutionPolicy -ExecutionPolicy unrestricted -Scope Process

4. Type A and press Enter.

change execution policy temporarily

5. Use the below command to navigate to the folder with the script file.

cd "C:\path\to\script\folder"

navigate to folder with PowerShell script

6. Enter the following command to run the script. If you used a different name for the script, change the command accordingly.

.\"DeleteOldFiles.ps1"

execute PowerShell script

As soon as you run the script, it will scan the folder and delete all the files that are older than the specified number of days. Once done, you will see the “Cleanup complete” message.

PowerShell script executed to delete files older than x days

Note: If you don’t want to change the execution policy every time you execute a PowerShell script, change the execution policy permanently.

Schedule the Script With Task Scheduler

If you want to run the PowerShell script on schedule (at a specific time or event), you can use Task Scheduler. I already wrote a detailed guide on how you can do that, follow the steps in that article.

Wrapping – PowerShell Automation Script for Deleting Old Files

As you can see, PowerShell automation makes deleting older files easy. While using the script, make sure you customize the folder path and number of days for the script to work correctly and according to your needs. Also, do keep in mind that when you run the script, the files are deleted permanently and there is no undoing it. So, be careful and test the script on a test folder before using it on a real folder. If you want to script to run automatically, use Task Scheduler to schedule it.

If you have any questions or need help, comment below. I will answer them.

Related:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top