Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Powershell Delete Files Older than X Days

Posted on 2015-01-22
7
Medium Priority
?
3,659 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 85

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 85

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 85

Accepted Solution

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

1

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
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…
Loops Section Overview

610 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