Solved

Powershell Delete Files Older than X Days

Posted on 2015-01-22
7
2,370 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 84

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 84

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
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.

 
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 84

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
AWK: Pythagoras bp script 18 28
Powershell script to find the HPOV version 4 26
Tricky powershell this time 4 26
Running powershell scripts from ASP.NET 6 31
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
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 a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

821 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