除了DOS中的某些文件外,如何删除所有文件/子目录?

Mar*_*eon 11 dos

我正在寻找一个DOS脚本来删除根目录中的所有文件和子目录,除了根目录中的一组批处理文件(*.bat).任何DOS都会在那里知道一个简单的方法吗?

更新

谢谢大家的帮助.这就是我现在所处的位置(见下文).我正在使用Ken的建议来删除文件.我想知道我怎样才能制止这种脚本运行,如果del还是RD命令失败,由于在文件/目录的锁.谁知道怎么样?现在,这个脚本将在删除后执行一些操作,如果任何删除失败,我想停止脚本.

@echo off

REM *********************************************************************
REM *  Delete all files and subdirs except for batch files in the root  *
REM *********************************************************************

REM Delete all files in current dir except bat files.  Does this by a) setting the attributes of *.bat files to 
REM readonly and hidden, b) deleting the rest, c) reseting the attributes 

attrib +r +s *.bat
del *.* /S /Q
attrib -r -s *.bat

REM Deletes ALL subdirectories 

FOR /D  %%G in (*) DO RD /s /q %%G
Run Code Online (Sandbox Code Playgroud)

Ken*_*ite 21

您可以先将要保留的文件的属性设置为只读和隐藏,然后删除其余文件,然后重置隐藏的只读文件的属性.

attrib +r +s *.bat
del *.*
attrib -r -s *.bat
Run Code Online (Sandbox Code Playgroud)

我曾经经常这样做,并写了一个自动化的批处理文件:

@echo off
@ if "%1" == "%9" goto help
@ if /i %1 EQU ? goto help
@ if /i %1 EQU help goto help
@ attrib +h +s %1
@ %2 %3 /Q
@ attrib -h -s %1
@ goto :EOF
:help
@echo        ?????????????????????????????????????????????????????????
@echo        ? except filespec1 doscommand filespec2                 ?
@echo        ?                                                       ?
@echo        ?  filespec1  The files to exclude from doscommand      ?
@echo        ?  doscommmand The DOS command to execute on filespec2  ?
@echo        ?  filespec2  The files to execute doscommand against   ?
@echo        ?                                                       ?
@echo        ? Example:                                              ?
@echo        ?                                                       ?
@echo        ? except *.txt del *.*                                  ?
@echo        ?                                                       ?
@echo        ?Deletes all files except text files in the directory   ?
@echo        ?????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

可能只是使用隐藏属性,但我知道del不会触及隐藏的系统文件,所以我设置了两个.IMO,比抱歉更安全.

基于Marcus的评论:如果您想将此扩展为包含当前目录的子目录,只需将两个attrib行更改为

attrib <remainder of line>  /S
Run Code Online (Sandbox Code Playgroud)

并将两条属性线之间的线更改为

@ %2 %3 /Q /S
Run Code Online (Sandbox Code Playgroud)

除了.bat之外,这应该适用于你想要的大多数事情.