Batch file to delete folder and its contents
I'm trying to write a batch file that would loop through a directory and delete any folder that is called \SAMPLE
.
Here is my code so far, any help would be greatly appreciated!
@echo off
title WAIT !
Set "sourceDir=z:\FOLDERS"
IF NOT EXIST "%sourceDir%" (echo.Could not find %sourceDir% & GoTo:done)
:: delete files
For /F "Delims=" %%! in ('Dir "%sourceDir%\") do (
rd "%%!" /s /q "%sourcedir%\ * \SAMPLE"
)
:done title,Done.......
echo.&pause>nul
for /d /r Z:\Folders %d in (SAMPLE) do if exist "%d" rd /s /q "%d"
You'll need to use %%d in a batch file, but that's the basic form. I've used similar constructs for cleaning up Subversion working directories to remove the .svn folders.
Edit: Fixed the syntax of the for command. I was working from memory and away from a Windows system at the time I posted. Sorry.
The Cadillac answer to this question. I wrote it up as a batch script which takes in option parameters and has a bit of configuration which may help OP and others who want to do slightly different things. The echo statements are optional and can be deleted if you don't want any output on the operation. Let me know if there are any bugs.
Sample of how this might work
This example has the wildcard option set to true, see the code below for more info
dir D:\deltest
Wed 04/03/2013 07:05 PM <DIR> KEEPME
Wed 04/03/2013 07:05 PM <DIR> SAMPLE
Wed 04/03/2013 07:05 PM <DIR> SAMPLE2
delete-sample-dir.bat d:\deltest
Searching for *SAMPLE* in D:\deltest
Deleting the folder D:\deltest\SAMPLE
Deleting the folder D:\deltest\SAMPLE2
dir D:\deltest
Wed 04/03/2013 07:05 PM <DIR> KEEPME
Code for delete-sample-dir.bat
@echo off
REM set the name of the directory you would like to target for deleting
set dirname=SAMPLE
REM set the following to "true" if you want to select any directory that includes the name, e.g., a wildcard match
set usewildcard=true
REM --DO NOT EDIT BELOW THIS LINE---------------
REM sentinel value for loop
set found=false
REM If true surround in wildcards
if %usewildcard% == true (
set dirname=*%dirname%*
)
REM use current working directory or take the directory path provided as the first command line parameter
REM NOTE: do not add a trailing backslash, that is added in the for loop, so use "C:" not "C:\"
set directorytosearch=%cd%
if NOT "%1%" == "" (
set directorytosearch=%1%
)
echo Searching for %dirname% in %directorytosearch%
REM /r for files
REM /d for directories
REM /r /d for files and directories
for /d %%i in (%directorytosearch%\%dirname%) do (
IF EXIST %%i (
REM change the sentinel value
set found=true
echo Deleting the folder %%i
REM Delete a folder, even if not empty, and don't prompt for confirmation
rmdir /s /q %%i
)
)
REM logic to do if no files were found
if NOT "%found%" == "true" (
echo No directories were found with the name of %dirname%
)