Search code examples
windowsbatch-filedirectoryrmdirdelete-directory

Delete all files in directory except .bat


I want to delete a specific directory on Windows. I use the code below. It works fine. I want to put the .bat file I made for this process in that directory. Naturally, the .bat file is also deleted. I want the .bat file to be excluded from this deletion. What should I do with the code?

Echo batch file delete folder
@RD /S /Q "D:\testfolder" 

Solution

  • There are several ways to achieve your task.

    The method, (especially as you generally remove directories with one command, and delete files with another), is to identify the files and subdirectories separately. First identify the subdirectories and remove those, using the RD command, then delete all files except for the batch file itself, %0:

    You could do that in one line using the ForFiles utility:

    @%SystemRoot%\System32\forfiles.exe /P "%~dp0." /C "%SystemRoot%\System32\cmd.exe /C If @IsDir==TRUE (RD /S /Q @File) Else If /I Not @file == \"%~nx0\" Del /A /F @File"
    

    Or you could use a For loop, with the Dir command:

    @For /F Delims^=^ EOL^= %%G In ('Dir /B /A "%~dp0"') Do @If "%%~aG" GEq "d" (RD /S /Q "%%G") Else If /I Not "%%G" == "%~nx0" Del /A /F "%%G"
    

    Please note that you can only remove/delete items for which you have the required permissions.