Home > front end >  Keep 10 most recent folders and delete the others
Keep 10 most recent folders and delete the others

Time:11-02

I have this cmd file, where I create a backup of a database

@echo off
Title Get FileName With Date and Time
Call :GetFileNameWithDateTime MyCurrentDate
echo %MyCurrentDate%
cd backups
MkDir %MyCurrentDate%
cd ..
cd bin
mysqldump.exe -u -p --single-transaction --routines --triggers --host test.com --databases database1 > "../backups/%MyCurrentDate%/testBackup.sql"
pause & exit
::----------------------------------------------------------------------------------
:GetFileNameWithDateTime <FileName>
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set "MyDate=%%x"
set "%1=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%"
Exit /B
::----------------------------------------------------------------------------------

So What I'm trying to do is creating a script, which only alllows 10 folders to exist, and the 10 folders should always be the latest. So if a 11 backup folder is made, then delete the oldest folder (1), and keep the latest (10)

enter image description here

CodePudding user response:

Made a solution that works, where I skip the first 10, and if there is more than that, then we delete.

set "delMsg="
for /f "skip=10 delims=" %%a in (
  'dir "backups\*" /t:c /a:d /o:-d /b'
) do (
  if not defined delMsg (
    set delMsg=1
    echo More than 10 found - only the 10 most recent folders will be preserved.
  )
  rd /s /q "backups\%%a"
)

CodePudding user response:

This seems more concise in PowerShell. This is written for a .bat fie script. When you are confident that the correct directories will be deleted, remove the -WhatIf from the Remove-Item command.

powershell -NoLogo -NoProfile -Command ^
    Get-ChildItem -Directory 'C:\backup\*' | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 10 | Remove-Item -Recurse -WhatIf
  • Related