PowerShell Basics: How to Delete Files Older Than X Days

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Tech Community.

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 storage devices of files not touched in over 6 months to clear up storage 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:\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 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 automation scripts to possibly add to or better the script shared above.

Leave a Reply

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

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.