Improve company productivity with a Business Account.Sign Up


Powershell Delete Files Older than X Days

Posted on 2015-01-22
Medium Priority
1 Endorsement
Last Modified: 2015-02-17
I am in need of a script that performs the following:
Delete files older than X days for all files that live in the top level folder as well as any files older than X days in any child subfolders.    Thanks.  

Top Level Folder
                 ---- Dir5
Question by:stressedout2004

Expert Comment

by:Matt Salo
ID: 40564461
This is a pretty basic script, but it should do what you need.

Just adjust the $path to the top level folder you want to work with, and adjust the $daysback to your desired days.

# Delete all Files in C:\temp older than 30 day(s)
$Path = "C:\temp"
$Daysback = "-30"

$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse ( | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

Open in new window

LVL 86

Expert Comment

ID: 40564469
Try this; you can pass the folder to start in as -Path, and the days to keep as -Days (or just set the default values to whatever you want). The script supports the -WhatIf switch as well, so if you run ".\Some-ScriptName.ps1 -Path C:\Temp -Days 3 -WhatIf", you'll see a list of files it would delete, without actually deleting anything.
	[string]$Path = "C:\Temp\DeleteMe",
	[string]$Days = 3
If (-Not (Test-Path -Path $Path)) {
	"Path '$Path' not found!" | Write-Error
	Exit 1
Get-ChildItem $Path -Recurse |
	? {-Not $_.PsIsContainer -And ($_.LastWriteTime -lt (Get-Date).AddDays(-$Days))} |

Open in new window

LVL 86

Expert Comment

ID: 40564484
Matt Salo,
your script will find all folders with the given difference to the LastWriteTime as well, and remove all contents found in there (unless the folder(s) in question have a subfolder, which would prompt a confirmation).
Building an Effective Phishing Protection Program

Join Director of Product Management Todd OBoyle on April 26th as he covers the key elements of a phishing protection program. Whether you’re an old hat at phishing education or considering starting a program -- we'll discuss critical components that should be in any program.


Expert Comment

ID: 40576318
You can do this without powershell too:

forfiles -p "%DIRECTORY%" -s -m *.* /D -%DAYS% /C "cmd /c del @path"

Open in new window


Author Comment

ID: 40597716
Why does Matts script not delete sub folders indicated by oBdA?  What is the final product of Matts script to support the requirements?

Author Comment

ID: 40597724
Matt I tested your script and it seems to work.   The folder was 4GB and I set the days to 60 and it is now half the size.     I don't understand what oBdA is referring to.  Can you confirm?
LVL 86

Accepted Solution

oBdA earned 1500 total points
ID: 40597807
I didn't say that Matt's script would "not delete sub folders".
I said that Matt's script could delete more than you bargained for, that is, complete folders (including files newer than the cutoff date) instead of single files.
Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
only checks the date, not whether the item retrieved is a directory or a file, so the script will attempt to delete directories with a time stamp older than the cutoff date as well. If these directories contain files newer than the cutoff date (and you confirm the delete operation), these files will obviously be deleted as well.
Here's a script that demonstrates the issue; set $TestRoot to a folder that does not exist yet (as its contents will be deleted).
Lines 1-22 build the test structure and inform about what happens.
Line 23 waits for input, so that you can check the test structure in Explorer.
Lines 25-31 are (mostly) Matt's script, with the source folder changed and the error in line 7 corrected.
If you confirm the following folder deletion, foo.txt will be gone, even though it had today's date.
$TestRoot = "C:\Temp\DeleteMe"
## Create the test directory structure
$DirTestRoot = New-Item -ItemType Directory -Path $TestRoot | Out-Null
$DirImportant = New-Item -ItemType Directory -Path "$($TestRoot)\Important"
$FileImportant = New-Item -ItemType File -Path "$($TestRoot)\Important\foo.txt"
## Pretend the subfolder with an important file has been created 3 months ago:
$DirImportant.LastWriteTime = (Get-Date).AddDays(-90)
$FileImportant.LastWriteTime = (Get-Date).AddDays(-90)

## Update the file with new content:
$DirImportant = Get-Item -Path "$($TestRoot)\Important"
$FileImportant = Get-Item -Path "$($TestRoot)\Important\foo.txt"
"The important file currently has a last write time of $($FileImportant.LastWriteTime)." | Write-Host
"The directory currently has a last write time of $($DirImportant.LastWriteTime)." | Write-Host
"Will update '$($FileImportant.FullName)' ..." | Write-Host
"Some new line added $(Get-Date)." | Add-Content -Path $FileImportant.FullName
"... content written." | Write-Host
## Since no new file was added, the folder's time stamp will not be updated:
$DirImportant = Get-Item -Path "$($TestRoot)\Important"
$FileImportant = Get-Item -Path "$($TestRoot)\Important\foo.txt"
"File '$($FileImportant)' now has a last write time of $($FileImportant.LastWriteTime)." | Write-Host
"Directory '$($DirImportant)' still has a last write time of $($DirImportant.LastWriteTime)." | Write-Host
Read-Host -Prompt "Press Enter to run the Delete script"

# Delete all Files in C:\temp older than 30 day(s)
$Path = $TestRoot
$Daysback = "-30"

$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

Open in new window


Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Welcome to 2018! Exciting things lie ahead in the world of tech. To start things off, we compiled great member articles on how to stay safe, ways to learn, and much more! Read on to start your new year right.
Excel allows various different methods to link Excel files to each other. This includes relative paths, mapped drives (or the local drive) and UNC paths. UNC paths are the least robust of the three.
In a recent question ( here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Screencast - Getting to Know the Pipeline

595 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question