I'm trying to delete all files and directories in a specific directory using a bat file in said directory. I've seen this done on Linux without problem, but in Windows command environment it seems to be a chore.
Example: \temp\1.bat (keep) \temp\special folder (keep)
Inside \temp\ contains all the folders and files I want to delete except the 1.bat and the special folder.
I have tried recursive commands but they delete the directory, or they delete all the files and keep the directories.
Example:
attrib +r "special directory"
attrib +r "1.bat"
erase /Q *.*
rd /s /q
attrib -r "1.bat"
Run Code Online (Sandbox Code Playgroud)
But this remove everything. If I remove the rd line, it removes all the files, not the directories and keeps the 1.bat file (like I need).
I've also tried:
for /d %%i in (".\*") do if /i not "%%i"=="special folder" rd /s /q "%%i"
Run Code Online (Sandbox Code Playgroud)
But this doesn't work either. I simply cannot get all the directories and files to be deleted except for the "special folder" and the "1.bat file".
Is this even possible?
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "keepfile=1.bat"
SET "keepdir=keep me"
FOR /d %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepdir%" RD /S /Q "%%a"
FOR %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepfile%" DEL "%%a"
GOTO :EOF
Run Code Online (Sandbox Code Playgroud)
您需要更改的设置sourcedir,keepdir并keepfile以适合你的情况。该列表使用了适合我的系统的设置。
该for/d命令处理所有目录,除了名称+扩展名与所需名称匹配的目录,然后for对目标目录中的文件重复操作,删除除与所需文件名匹配的所有目录以保留。
| 归档时间: |
|
| 查看次数: |
8627 次 |
| 最近记录: |