PowerShell Basics: How to Delete Files Older Than X Days

Currently spring cleaning your home… or trying to find something to do while stuck at home?  I've recently taken up the task to clean my NAS and other devices of files not touched in over 6 months to clear up space.  I once again turn to PowerShell to automate the task.  

Lets begin.

The following script will delete items in my Downloads directory that are older than 6 months:

$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:logdeletedlog.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:logdeletedlog.txt -Append
}

The latter half of the script deletes any folders or subfolders now empty after the purge.  A deletelog.txt file is created to report on all file and folders that have now been removed.

As always, please share below your PowerShell to possibly add to or better the script shared above.

 

This article was originally published by Microsoft's ITOps Talk Blog. You can find the original article here.