Batch Script to delete oldest folder in a given folder

前端 未结 4 2013
情书的邮戳
情书的邮戳 2021-01-12 12:24

I\'m writing a simple .bat backup script, and as part of it I want the oldest backup (folder) to be deleted upon reaching a set max limit of backups.

Right now I hav

相关标签:
4条回答
  • 2021-01-12 12:53

    You were so close ! :-)

    All you need to do is skip the first %MAXBACKUPS% entries when sorted by date descending. You don't even need your COUNTER variable.

    :: Preserve only the %MAXBACKUPS% most recent backups.
    set "delMsg="
    for /f "skip=%MAXBACKUPS% delims=" %%a in (
      'dir "..\Backup\*" /t:c /a:d /o:-d /b'
    ) do (
      if not defined delMsg (
        set delMsg=1
        echo More than %MAXBACKUPS% found - only the %MAXBACKUPS% most recent folders will be preserved.
      )
      rd /s /q "..\Backup\%%a"
    )
    
    0 讨论(0)
  • 2021-01-12 12:56

    A simple way to do this based on your script:

    FOR /f "delims=" %%a in ('dir "..\Backup\*" /t:c /a:d /o:-d /b') do set lastfolder=%%a
    
    rd /s /q "..\Backup\%lastfolder%"
    

    So you still loop over each folder, sorted by age, but you overwrite %lastfolder% so at the end it contains only the name of the oldest folder.

    Then you delete that folder.

    0 讨论(0)
  • 2021-01-12 12:58

    Here's the final block of code I ended up using:

    :: Preserve only the %MAXBACKUPS% most recent backups.
    FOR /f "skip=%MAXBACKUPS% delims=" %%a in (
    'dir "..\Backup\*" /t:c /a:d /o:-d /b'
    ) do (
    ECHO More than %MAXBACKUPS% backups found--Deleting "%%a".
    ECHO.
    rd /s /q "..\Backup\%%a"
    )
    

    It simplifies the deletion message code a bit, and provides the end user with info about what file was deleted in the command prompt window.

    Based on dbenham's answer.

    0 讨论(0)
  • 2021-01-12 13:04
    FOR /f "delims=" %%a in ('dir "..\Backup\*" /t:c /a:d /o:d /b') do (
     rd /s /q "..\Backup\%%a"
     goto :break
    )
    :break
    

    you can break the for loop with goto

    0 讨论(0)
提交回复
热议问题