0
votes

I'm new at PowerShell and don't know so much about it.

I'm searching for a way to delete a folder and all sub-folders if all files in this are older than x days. I have an code to delete all files in a folder and all sub-folders but I don't know how to change it right.

$Now = Get-Date

$Days = "30"

$TargetFolder = "C:\temp"
$Extension = "*.*"
$LastWrite = $Now.AddDays(-$Days)

$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {($_.CreationTime -le "$LastWrite") -and ($_.LastWriteTime -le "$LastWrite")}


foreach ($File in $Files) 
    {
    if ($File -ne $NULL)
        {
        write-host "Deleting File $File" -ForegroundColor "Red"
        Remove-Item $Location.FullName | out-Null
        }
    else
        {
        Write-Host "No more files to delete!" -foregroundcolor "Green"
        }
    }
1
created 30 days ago or modified?4c74356b41
Both must be respected, because if you downloaded a File in 2015 the ModifieDate is 2015 and you moved it to "C:\temp" in 2017/22/02 than the CreationDate is that an i dont whant to remove it.Bl4cKh4wK ZG
copying a file doesn't modify the creation date or writetime, not sure how you want to achieve that4c74356b41
ok than lets say created 30 day ago :)Bl4cKh4wK ZG

1 Answers

1
votes

Enumerate all folders and sort them longest path first, so you process the directories bottom to top:

Get-ChildItem $TargetFolder -Recurse -Directory |
    Select-Object -Expand FullName |
    Sort-Object Length -Desc

Filter the list for directories that don't have any file or folder newer than x days in them:

... | Where-Object {
    -not $(Get-ChildItem $_ -Recurse | Where-Object {
        $_.Creationtime -ge $LastWrite -or
        $_.LastWriteTime -ge $LastWrite
    })
}

Then remove the resulting folders:

... | Remove-Item -Recurse -Force