Search code examples
powershellfilerecursion

Powershell Recursively List or Delete Files older than 30 days include all files in folders in the subtree regardless of when the folder was modified


I am using powershell to delete files in folders that are last modified older than 30 days. (LastWriteTime). My script works if the files are in the path specified but not if they are in a subfolder of that root path. It seems the folder has been considered in the script and I am at a loss as to why. I get one file returned out of 2000 files that were created, modified, accessed 4 months ago.

My folder structure is: P:\Root/SubFolderRoot/SubFolder1/SubFolder1 ..-.. SubFolder9 There are multiple subs and any of them can contain files older than 30 days.. I am only interested in the files older than 30 days regardless of the Folder Modified, Accessed, Created Times. I have searched on stack and can provide several almost exact code examples to mine but they do not work.

$folderTree = 'P:\Root\SubFolderRoot'
$refDate = (Get-Date).AddDays(-30)
Get-ChildItem -Path $folderTree -File -Recurse | 
    Where-Object {-not $_.PSIsContainer -and $_.LastWriteTime -lt $refDate } 
    | foreach-object { Write-Host  $_.FullName }

# Where-Object { $_.LastWriteTime -lt $refDate } 
# Select-Object FullName

Solution

  • $folderTree = 'P:\Root\SubFolderRoot'
    $refDate = (Get-Date).AddDays(-30).Date
    Get-ChildItem -Path $folderTree -Filter * -File -Recurse | 
        Where-Object { $_.LastWriteTime -lt $refDate } |
        Remove-Item -WhatIf
    

    Should do what you want.
    Using the -WhatIf switch will cause the code to not delete anything, just output in the console what would happen. Once you are satisfied the correct files are listed, take off the -WhatIf switch and run again.