Powershell script to delete sub folders and files if creation date is >7 days but maintain parent folders of sub folders and files <7 days old
- by Mark
I'm currently using the Powershell script below to delete all files directories and sub directories of "$dump_path" that are seven days or older based upon the creation date and not modified date.
The problem with this script is this:
If folder "A" is seven (or more) days old it will be deleted even if its sub folders and files are less then seven days old.
What I would like this script to do is this:
Delete all files from the root and in all sub folders of "$dump_path" that are seven or more days old but maintain the parent folder(s) of files and folders that are less than seven days old even if that means the parent folders are more than seven days old. If all subfolders and files are seven days or older than the parent folder then the parent can be deleted.
Slightly obscure problem I know, but the intention is to have a 7 day retention period of all data in a 'sandbox' location of our shared areas.
Also, an added bonus if it could generate a log of what it deletes and e-mails it out post deletion.
Thank you for reading and I hope that all makes sense!
Mark
# set folder path
$dump_path = "c:\temp"
# set minimum age of files and folders
$max_days = "-7"
# get the current date
$curr_date = Get-Date
# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)
# delete the files and folders
Get-ChildItem $dump_path | Where-Object { $_.CreationTime -lt $del_date } | Remove-Item -Recurse