Tuesday, 3 April 2012

Batch files which delete specific directories and files

I have many projects on my disk and usually, even if not working on them any more, keep IDE-generated user- or IDE session-specific files (with extensions sdf, sbr, suo, ilk...) as well as project build outputs which are in various directories (named Debug, Release, bin, obj...depending on the type of the project). They can use lots of disk space so I created several scripts to automatize removing these directories and files.

Script that deletes all subdirectories of a specific name - delete_dir.bat:

@ECHO OFF
IF "%1" == "" GOTO ERROR1
ECHO Deleting subdirectories with name "%1":
FOR /r /d %%D IN (%1) DO (
   if exist %%D (
      echo Deleting "%%D"
      RMDIR /S /Q "%%D"
   )
)
GOTO END
:ERROR1
ECHO ERROR: Directory name not specified
ECHO Usage: delete_dir.bat <dir_name>
ECHO Script removes all subdirectories with name <dir_name>
:END

Script that deletes all files with a specified extension - delete_files_with_ext.bat:

@ECHO OFF
IF "%1" == "" GOTO ERROR1
ECHO Deleting files with extension "%1":
FOR /F "tokens=*" %%F IN ('dir *.%1 /s /b') DO (
   echo Deleting "%%F"
   del "%%F"
)
GOTO END
:ERROR1
ECHO ERROR: File extension not specified
ECHO Usage: delete_files_with_ext.bat <ext_name>
ECHO Script deletes all files with extension <ext_name> that are contained in the current directory or its subdirectories.
:END

Script that calls previous scripts in order to perform deleting Visual Studio-generated user-specific, IDE-session specific and build output directories and files - clean_all.bat:

@ECHO OFF
ECHO Script removes all subdirectories with names: Debug, Release, ipch, bin, obj and files with extensions sdf, pch, obj
call delete_dir.bat Debug
call delete_dir.bat Release
call delete_dir.bat ipch
call delete_dir.bat bin
call delete_dir.bat obj
call delete_file_ext.bat sdf
call delete_file_ext.bat pch
call delete_file_ext.bat obj

Links and references:
Windows CMD

1 comment:

Unknown said...

Great article. I'm using it to clean up all our feature branches. They could take up to several GB's of space...