Delete files older than X days with Powershell

Change the folder in the variable $folder to the directory of your choice.

To specify dates behind today’s date change the (-180) to however many days you need (-7) is 1 week.

$Folder = "G:\Downloads"

#Delete files older than 6 months
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-180)} |
ForEach-Object {
   $_ | del -Force
   $_.FullName | Out-File C:\log\deletedlog.txt -Append
}

#Delete empty folders and subfolders
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {$_.PsIsContainer -eq $True} |
? {$_.getfiles().count -eq 0} |
ForEach-Object {
    $_ | del -Force
    $_.FullName | Out-File C:\log\deletedlog.txt -Append
}

The out-file command writes all discovered filenames that are deleted and writes it out to a log file.

If you’re feeling up to it, now this script needs a built-in log cleanup to remove all of the old entries in the log file.

Leave a Reply

Your email address will not be published. Required fields are marked *