The script Remove-Files is used to remove old and/or obsolete files from the target directory. It can delete files that are older than a specified amount of time or older than a specified date or it can delete the oldest files in the directory keeping any number of recent files.
 
Help is included in the script and can be retrieved using get-help remove-files.ps1
 
The script was writen using PowerShell V2.0 and supports the -whatif and -confirm parameters.
 

 

Update #1:

In the updated version a file extension filter has been added so the script can be targeted to delete only old files of a certain type.

 

Update #2:

The parameter KeepFiles can now be used in combination with KeepDays or Date. If you combine KeepDays or Date with KeepFiles a number of n newest files will be kept regardless if they are older than the amount of days or date specified.
So let's say you have a backup running and only want to keep the last 7 days of your backup files.
Normaly you would use
PowerShell
Edit|Remove
.\remove-files.ps1 -Path Backup -Extension .bak -KeepDays 7
But whatif your backup hasn't been running for let's say 14 days. All your files would have gotten deleted leaving you with no backup at all. So KeepFiles comes to the rescue.
If you combine the two parameters like this
PowerShell
Edit|Remove
.\remove-files.ps1 -Path .\Backup -Extension .bak -KeepDays 7 -KeepFiles 3
Now all but the most recent 3 files will be deleted even if they are older than 7 days. Leaving you something to restore in case you need it.
 
Here are some more usage examples:
PowerShell
Edit|Remove
.\Remove-Files.ps1 -Path .\Testing -KeepFiles 3 - Recurse 
 
Description 
----------- 
Removes all but the newest 3 files from the directory .\Testing and all subdirectories 
 
.\Remove-Files.ps1 -Path .\Testing -KeepDays 7 
 
Description 
----------- 
Removes all files older 7 days from the directory testing 
 
$date = (get-Date).AddMonth(-1) 
.\Remove-Files.ps1 -Path .\Testing -Date $date -Extension *.txt 
 
Description 
----------- 
Removes all textfiles older than one month from directory .\Testing 
 

BugFix #1:

There was a logical error in the handling of the combination of the -KeepDays/KeepDate and-KeepFiles parameters.Under certain circumstances it was possible that either not all files that should have been deleted were actually deleted and (worse) the -KeepFiles parameter was ignored and all files that were older than KeedDays/KeepDate were actually deleted.
Fixed this by changing the Remove-Before function.