Solved

Powershell Delete Files Older than X Days

Posted on 2015-01-22
7
1,685 Views
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
--Dir1
--Dir2
--Dir3
         ---Dir4
                 ---- Dir5
--Dir6
--Dir7
1
Comment
Question by:stressedout2004
7 Comments
 

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

1
 
LVL 83

Expert Comment

by:oBdA
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.
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
	[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))} |
	Remove-Item

Open in new window

1
 
LVL 83

Expert Comment

by:oBdA
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).
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Expert Comment

by:mouseware
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

1
 
LVL 9

Author Comment

by:stressedout2004
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?
0
 
LVL 9

Author Comment

by:stressedout2004
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?
0
 
LVL 83

Accepted Solution

by:
oBdA earned 500 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

1

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
Synchronize a new Active Directory domain with an existing Office 365 tenant
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now