I want to have a batch file that will delete all the folders and files in my cache folder for my wireless toolkit.
Currently I have the following:
cd
You could use robocopy to mirror an empty folder to the folder you are clearing.
robocopy "C:\temp\empty" "C:\temp\target" /E /MIR
It also works if you can't remove or recreate the actual folder.
It does require an existing empty directory.
You cannot delete everything with either rmdir
or del
alone:
rmdir /s /q
does not accept wildcard params. So rmdir /s /q *
will error.del /s /f /q
will delete all files, but empty subdirectories will remain.My preferred solution (as I have used in many other batch files) is:
rmdir /s /q . 2>NUL
You can do this using del
and the /S
flag (to tell it to recurse all files from all subdirectories):
del /S C:\Path\to\directory\*
The RD command can also be used. Recursively delete quietly without a prompt:
@RD /S /Q %VAR_PATH%
Rmdir (rd)
I just put this together from what morty346 posted:
set folder="C:\test"
IF EXIST "%folder%" (
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)
It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.
Just a modified version of GregM's answer:
set folder="C:\test"
cd /D %folder%
if NOT %errorlevel% == 0 (exit /b 1)
echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
pause
REM First the directories /ad option of dir
for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)
REM Now the files /a-d option of dir
for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)
REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.
Use:
Create a batch file
Copy the below text into the batch file
set folder="C:\test"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
It will delete all files and folders.