Batch file that keeps the 7 latest files in a subfolder

非 Y 不嫁゛ 提交于 2019-12-08 08:22:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!