I'm looking for a DOS script to delete all files and subdirectories in a root directory except for a set of batch files (*.bat) that are in the root directory. Any DOS jocks out there that know an easy way to do this?
Update
Thanks for your help everyone. This is where I'm at now (see below). I'm using Ken's suggestion for the delete of the files. I would like to know how I can stop this script running if the del
or RD
commands fail due to a lock on a file/dir. Anyone know how? Right now, this script will do a bunch of things after the deletes and I'd like to stop the script if any of the deletes fail.
@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
YOu can set the attributes of the files you want to keep to readonly and hidden first, delete the rest, and then reset the attributes of the hidden, readonly files back.
attrib +r +s *.bat
del *.*
attrib -r -s *.bat
I used to do that quite often, and wrote a batch file that automated this:
@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 ╚═══════════════════════════════════════════════════════╝
It's probably OK just to use the hidden attribute, but I know that del doesn't touch hidden system files, so I set both. Better safe than sorry, IMO.
Based on a comment from Marcus: If you want to extend this to include subdirectories of the current directory, simply change both attrib lines to
attrib <remainder of line> /S
and change the line between the two attrib lines to
@ %2 %3 /Q /S
That should work for most things you'd want except.bat to do.