How to Delete Files Over (N) Days Old But Leave (N) Files Regardless of Age

Windows batch file delete files older than X days but leave a min of X files

This script will delete all zip and log files older than 14 days, keeping a minimum of the 5 most recent of each (10 total), regardless of age.

Note that the FORFILES /D option is based on last modified date, so I did not use creation date for ordering my DIR command.

The FORFILES command is quite slow, so once I detect the a file older than 14 days old, I don't bother running FORFILES again, since I know all remaining files are that age or older.

@echo off
pushd "c:\yourBackupPath"
for %%X in (zip log) do (
set "skip=1"
for /f "skip=5 delims=" %%F in ('dir /b /a-d /o-d /tw *.%%X') do (
if defined skip forfiles /d -14 /m "%%F" >nul 2>nul && set "skip="
if not defined skip del "%%F"
)
)

delete if 30days old by folder name

Try using the [DateTime]::ParseExact() method, it's much simpler for your purposes:

function Delete-Folder-30days{
gci "\\$args\Apps\AndrewTest" -Directory | ?{[datetime]::ParseExact($_.Name,"MMddyyyy",$null) -lt (get-date).AddDays(-30)} | Remove-Item -Recurse
}

Delete-Folder-30days $Server

Edit: Sorry! Had the String and Format switched (should be like ("04122014","MMddyyyy",$null)) but I had the first two arguments reversed.

Edit2: You want it to include .zip files as well? There's a couple of things. If you want to include all files then it is really simple. Just remove the -Directory from the GCI command and it will look at all files and folders in the target directory. If you ONLY want folders and .ZIP files then it gets a little more complicated. Basically we will still remove the -Directory switch, but we'll have to add some filtering into the Where clause as such:

?{($_.PSIsContainer -and [datetime]::ParseExact($_.Name,"MMddyyyy",$null) -lt (get-date).AddDays(-30)) -or ($_.Extension -ieq ".zip" -and [datetime]::ParseExact($_.BaseName,"MMddyyyy",$null) -lt (get-date).AddDays(-30))} 

So now instead of just checking the specially formatted date, you are asking Is this a folder, or does it have the .zip file extension? If at least one of those two is true, does it match the specially formatted date?

Keep x number of files and delete all others - Powershell

You can sort by CreationTime descending and skip the first 10. If there are less than 10 files it will not remove any.

gci C:\temp\ -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc| 
select -Skip 10| Remove-Item -Force


Related Topics



Leave a reply



Submit