简体   繁体   中英

Manage Windows directory using batch(sorting and deleting)

I want to create a batch file that will sort the files(based on created date) in a directory and only keep x number of the most recent files.

The files also have a date/time in their names(ie. file201208140322) so if it's possible doing this by comparing current date/time to the substring I am open to this as well.

Can anybody help me with the command? Thank you for your help.

You can use DIR /OD /B /AD to get a list of files sorted in descending modification time, then feed the output of this command to FOR /F so that you get to process these files. Using SET /A you can increment a counter that keeps track of how many files we have seen so far, and after this counter reaches a certain threshold you can start deleting all subsequent entries.

Here's a batch file that does this:

@ECHO OFF
SETLOCAL
SET PROCESSED_COUNT=0
SET SKIP_FIRST=5
SET START_PROCESSING=0
FOR /F %%f IN ('dir /o-d /b /a-d') DO CALL :process %%f
ENDLOCAL
GOTO :eof

:process
IF %PROCESSED_COUNT%==%SKIP_FIRST% SET START_PROCESSING=1
SET /A PROCESSED_COUNT=%PROCESSED_COUNT% + 1
IF %START_PROCESSING%==0 GOTO :eof
ECHO Delete file #%PROCESSED_COUNT%: %1
GOTO :eof

There are also other possible variations on this theme, so the above is not the only solution.

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