Solved

Powershell Delete Files Older than X Days

Posted on 2015-01-22
7
2,129 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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

813 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

8 Experts available now in Live!

Get 1:1 Help Now