How to delete folder and files older than 60 days

I have an archive folder and tons of subfolders.
I am just wondering how to delete the folders and files files older than 60 days. Caution: If a file is not older than 60 days do not delete folder o folders but keep searching all the way down.

I have the following code but i think only works for files.
$limit60 = (Get-Date).AddDays(-60)
$path1 = "D:\Archive\Delivery"
Get-ChildItem -Path $path1 -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit60 } | Remove-Item -Force

Open in new window

namergSystems AdministratorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael JohnsonNetwork AnalystCommented:
Create a batch file and add it to your scheduled tasks.  Something like this:

forfiles /p "C:\File\Location" -s -m *.* /D -60 /C "cmd /c del @FILE"

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/forfiles
0
namergSystems AdministratorAuthor Commented:
Batch is an old technology . I need it in powershell.
0
Michael JohnsonNetwork AnalystCommented:
0
How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

namergSystems AdministratorAuthor Commented:
Will that script accomplish what i am asking ? I do not think it does. The code i posted does that.
0
Michael JohnsonNetwork AnalystCommented:
You have to read through the examples but I think you're looking for:

.EXAMPLE
.\deleteold.ps1 -FolderPath C:\docs -FileAge 30 -logfile h:\log.log -CreateTime -CleanFolders
 
Description:
Deletes all files that were created 30 days ago or before in the C:\docs folder. Only folders that contained old files and are empty after the deletion of those files will be deleted.
0
namergSystems AdministratorAuthor Commented:
Hmm, i was looking for a more intelligent script though without the need to add paramaters
0
DBAduck - Ben MillerPrincipal ConsultantCommented:
Your script works, but it won't do folders, because in the Where it has !$_.PsIsContainer which translates to a folder.  The creation time comparison is correct. If you want folders, you would want the folders to be empty right?

You could have created the folder 60 days ago, but files could have been put in there after the 60 days.  But you know your application better than we do. So if you want to delete a folder if it is in the same criteria, you can remove !$_.PsIsContainer and it will remove everything even folders.

Be aware that if the folder has files, then you would have to use the -Recurse parameter on the REmove-Item, not just the -Force.
0
footechCommented:
Side note - I wouldn't call a script that take arguments as parameters less "intelligent".  It's more flexible, not requiring code-changes each time a condition changes.

Moving on...
You may have to examine all the scenarios possible in your folder structure, like how and when folders are created.  It seems to me that you'll want to just delete any folders that are empty, without worrying about creation date (leave that condition to the files).  Whether you look at the date on the folders or not, you essentially have to go back a second time after deleting files to check all folders to see if they're empty, and you have to process them in the order of greatest folder depth to least (leaf to root).  Get-ChildItem will return items in the order root to leaf, and if you delete a folder using Remove-Item -recurse you can delete child items that don't meet the criteria.
Here's an example of deleting in the fashion I mentioned (remove -whatif to process for real), this would be run after the code to delete the files:
$FolderList = Get-ChildItem $path1 -Directory -Recurse | Select fullname | sort {(($_.fullname).split("\\")).count} -Descending
$Count = $FolderList.Count
for ($j=0;$j -lt $Count;$j++) {
    $TempFolder = Get-ChildItem -LiteralPath $FolderList[$j].FullName -ErrorAction SilentlyContinue -Force
    if (-not $TempFolder) {
        $TempName = $FolderList[$j].FullName
        Remove-Item -LiteralPath $TempName -Force -Recurse -ErrorAction SilentlyContinue -WhatIf
    }
}

Open in new window

1
namergSystems AdministratorAuthor Commented:
My bad, but the fact that the script will be part of a schedule task, adding parameters every time i wan to execute the schedule task, i do not see it efficient. I might be wrong though.

Let me rephrase my issue. I would like to delete files and folders that are older than 60 days. But what i have sees.... folders since 2015, just folders and no files. So, why keeping empty folders with no files ? i want to delete them also.

Thanks for your help,
0
footechCommented:
As a scheduled task, I wouldn't expect that you would be recreating it every time you want to run.  You would just run the already configured task.  And you could have more than one task, using the same script, but just specifying different parameters in the task (for example if you had different folders that you wanted to run the cleanup on).
Command:  powershell.exe
Arguments:  -file "c:\scripts\deleteold.ps1" -folderpath "D:\Archive\Delivery" -fileage 60 -cleanfolders -logfile c:\temp\pslog1.txt

I think you've just echoed my point.  No need to keep any folders if they're empty, regardless of the date on them.  Unless for some reason your application or process creates empty folders which need to be there.

Both my code and the script linked to by Michael Johnson will delete folders.
0
namergSystems AdministratorAuthor Commented:
hmm , you wrote "No need to keep any folders if they're empty, regardless of the date on them"...date matters. I have to treat them as files too. If they are older than x days delete them also and of course the files below of it are older too. It is kinda confusing what i am trying to express...
0
footechCommented:
Please answer these questions:

1) Look at all your folders in the tree you want this script to run against.  Are there any that are empty but have a date that is newer than the cutoff date (now - 60 days)?
2) Does your application or process create empty folders which need to be there?
0
namergSystems AdministratorAuthor Commented:
Answers below:

1) Look at all your folders in the tree you want this script to run against.  Are there any that are empty but have a date that is newer than the cutoff date (now - 60 days)? Yes, correct.

2) Does your application or process create empty folders which need to be there? Yes, but the timestamp will be newer. So, if the script is executed in the future (more than 60 days), the empty folders will be deleted.
0
DBAduck - Ben MillerPrincipal ConsultantCommented:
One more question.

1) Will there be a folder that is older than 60 days and still contain files that are NEWER than 60 days?
0
footechCommented:
A simple change to my code above will be sure to not delete folders that are newer than the cutoff date.
$FolderList = Get-ChildItem $path1 -Directory -Recurse | Where { $_.creationtime -gt $limit60 } | sort {(($_.fullname).split("\\")).count} -Descending

Open in new window

1
namergSystems AdministratorAuthor Commented:
@DBAduck
Will there be a folder that is older than 60 days and still contain files that are NEWER than 60 days?
Yes
0
footechCommented:
The script provided in #a42494509 will take care of all the files according to criteria, and with the author confirming that some empty folders should not be deleted, the code can be modified as in #a42498192 to accomplish that.

The script suggested by Michael can delete the files, but if set to delete folders will remove any that are empty regardless of timestamp.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

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.