问题
Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the latest 7 files (in other words, the newest) in the all folders from specify directory.
I got
set file2del=
for /f "skip=7" %%A in ('dir /b/o-d') do set file2del=%%A
if not "%file2del%"=="" del "%file2del%"
But this work for current directory.
回答1:
Try this :
First use FOR /D
with the /R
Switch to recursively loop on all folder (from where the bat is started). and apply the FOR /F
loop on each directory.
@echo off
for /d /r %%a in (*) do (echo Treating Diretory ==^> %%a
for /f "skip=7" %%b in ('dir /b/o-d "%%a"') do del "%%a\%%b"
)
If you need something more detailled you can use a counter in place of the SKIP=7
:
@echo off
setlocal enabledelayedexpansion
for /d /r %%a in (*) do (echo Treating Diretory ==^> %%a
set /a $count=1
for /f %%b in ('dir /b/o-d "%%a"') do (
if !$count! LEQ 7 (
echo Keeping File[!$count!] ==^> %%b
set /a $count+=1
) else (echo Deleting File ==^> %%a\%%b
del "%%a\%%b")
)
)
回答2:
set "specificDir=c:\temp\"
for /f "skip=7" %%A in ('dir /b /o-d /a-d "%specificDir%"') do del "%%~fA"
should do. I added /a-d
to exclude folders, used %%~fA
to get the complete filename including drive/path and put quotes around it to safely process filenames (or paths) with spaces.
来源:https://stackoverflow.com/questions/39830101/batch-file-that-keeps-the-7-latest-files-in-a-subfolder