简体   繁体   中英

Batch Script to delete only files with .zip extension

I want to skip the latest 3 files created and delete the rest of the files . What I need is that if there is text, xml and zip files we need to delete only the zip files and leave the text and xml files behind and the total files left should be 3.If there are 3 or more files other than .zip files, delete all .zip files; if there are less, keep the newest .zip files so that there are 3 files left in total. Can anyone help. I am stuck with this

For example(inside bracket created date of files): Folder A contains - aa.txt(2/1/18), bb.xml(3/1/18), cc.zip(4/1/18), dd.zip(2/1/18),ee.zip(5/1/18)

What I need after deleting is aa.txt, bb.xml, ee.zip

This is what I have written

@ECHO OFF
SETLOCAL
SET "targetdir=C:\source"
SET /a retain=3

FOR /f "skip=%retain%delims=" %%a IN (
 'dir /b /a-d /o-d "%targetdir%\*.zip" '
 ) DO DEL (DEL "%targetdir%\%%a.zip"

GOTO :EOF

Given the parameters of your question, a very simple method, although not the most efficient or speedy , would be to do this:

@Echo Off
Set "targetdir=C:\source"
Set "retain=3"
CD /D "%targetdir%" 2>Nul || Exit /B
For /F "Skip=%retain% Delims=" %%A In ('Dir /B/A-D/O-D/TC'
) Do If /I "%%~xA"==".zip" Del "%%A"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM