Delete folders over X days - Powershell


i have a folder structure which is in the YYYY\MM\DD\HH format

I have written Powershell script to delete all folders including the files contained within these files older than 7 days old.

my script is as follows:

$limit = (Get-Date).AddDays(-5)
$path = "G:\MYDOCS\Document"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

What i want to do is add some logging to thsi so that i can audit whats been deleted. Secondly is there a way i can delete folders which are older than say 12 hours at all?

synergytecHead of ITAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

Trent SmithCommented:
$Now = Get-Date
$Days = "2"
$TargetFolder = "D:\vmbackup"
$LastWrite = $Now.AddDays(-$Days)

$Folders = get-childitem -path $TargetFolder |
Where {$_.psIsContainer -eq $true} |
Where {$_.LastWriteTime -le "$LastWrite"}

    foreach ($Folder in $Folders)
    write-host "Deleting $Folder" -foregroundcolor "Red"
    Remove-Item $Folder -recurse -Confirm:$false
synergytecHead of ITAuthor Commented:
Hi, just tried it but it does not seem to be working. Nor any log file produced.
Trent SmithCommented:
Instead of having the fix with logging I found this thread on technet where it emails you upon error.

I will continue to see if I can get the logging portion for you.

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

From novice to tech pro — start learning today.