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

powershellscripting

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

# 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

Best Answer

May I suggest a slightly different approach? I'd delete all files older than 7 days first, and in a second step delete empty folders. Something like this:

$deleted = @()

Get-ChildItem $dump_path -Recurse | Where-Object {
  -not $_.PSIsContainer -and $_.CreationTime -lt $del_date
} | ForEach-Object {
  $deleted += $_.FullName
  $_
} | Remove-Item

function Remove-EmptyFolders($folder) {
  Get-ChildItem $folder | Where-Object { $_.PSIsContainer } | ForEach-Object {
    $path = $_.FullName
    Remove-Emptyfolders $path
    if ( @(Get-ChildItem $path -Recurse | Where-Object { -not $_.PSIsContainer}).Length -eq 0 ) {
      $deleted += $path
      Remove-Item $path -Recurse -Force
    }
  }
}

Remove-EmptyFolders $dump_path

$html = $deleted | Select-Object @{Name='Path';Expression={$_}} | ConvertTo-Html
Related Topic