.bat file to delete certain files

iwoodland

New Member
Joined
Jan 3, 2017
Messages
6
Hi all - just wondering if someone has some coding i could use for a batch file in windows


I have a back up folder and files automatically backup with a date and time at the end. Over time this becomes a long list. Can someone share some coding for a batch file that once there is more than 2 of a specific file name [taking into account the file name will have successive dates and times] and then delete them leaving only the 2 latest files of each of the different files in that folder. Only needs to work when i run the batch.

e.g. keep The 2 latest
Apple 2017-01-01 21.30.xls
Apple 2017-01-01 21.59.xls
Apple 2017-01-02 21.10.xls
Apple 2017-01-03 21.150.xls

and keep the 2 latest
Water 2017-01-01 21.30.mdb
Water 2017-01-01 21.59.mdb
Water 2017-01-02 21.10.mdb
Water 2017-01-03 21.15.mdb




Many thanks in anticipation


Ian
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK

RedBeard

Well-known Member
Joined
May 16, 2015
Messages
858
Powershell solution:

Code:
# Keeps latest 2 files from a directory based on Creation Time


#Declaration variables
$path = "C:\temp\"                               # For example $path= C:\temp\
$total= (ls $path).count - 2 # Change number 2 to whatever number of objects you want to keep


# Script


ls $path |sort-object -Property {$_.CreationTime} | Select-Object -first $total | Remove-Item -force

As always, try on a backup of your data.
 
Upvote 0

Forum statistics

Threads
1,191,361
Messages
5,986,203
Members
440,010
Latest member
cdotshel

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top