Batch file to delete all folders in a directory except a specified list

左心房为你撑大大i 提交于 2019-12-22 10:34:39

问题


I'm looking for a batch file that will go into C:\Documents and Settings\ and delete all folders except a few that I want to keep.


回答1:


Here's a hack-around =D

If you have a list of folder paths in say folders.txt listed as so:

  • C:\Documents and Settings\Mechaflash
  • C:\Documents and Settings\Mom
  • C:\Documents and Settings\Dad

etc. What you can do is temporarily change them to hidden folders, then RMDIR on all non-hidden folders.

CD "C:\Documents and Settings\"
FOR /F "tokens=*" %%A IN (folders.txt) DO (
 ATTRIB +H "%%A" /S /D
)
FOR /F "USEBACKQ tokens=*" %%F IN (`DIR /B /A:-HD "C:\Documents and Settings\"`) DO (
 RMDIR /S /Q %%A
)
FOR /F "tokens=*" %%A IN (folders.txt) DO (
 ATTRIB -H "%%A" /S /D
)



回答2:


A solution using robocopy:

cd /d "C:\Documents and Settings"
md tmp
robocopy . tmp /E /MOVE /XD folderToKeep1 folderToKeep2 ...
rd /s /q tmp



回答3:


rem the last space character is deliberate
set yourKeepList="abc def "
for /f %%f in ('dir /b/ad "C:\Documents and Settings"') do (
    (echo %yourKeepList% | findstr /v /i "%%f " 1>nul) && rd /q/s %%f
)


来源:https://stackoverflow.com/questions/7503194/batch-file-to-delete-all-folders-in-a-directory-except-a-specified-list

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