Home > Mobile >  How to make a batch file delete all files and subfolders in a specific directory?
How to make a batch file delete all files and subfolders in a specific directory?

Time:10-21

I want a batch file to delete all the files and subfolders in the directory it's in. This is what I made (it deletes just files):

cd "%~dp0"
for %%i in (*.*) do if not "%%i"=="%~nx0" del /f /q "%%i"

How to make it delete also subfolders?

CodePudding user response:

It's a known problem in Windows commandline: in order to remove a file, you need the del command. In order to remove a directory, you need rmdir but you can only launch that command if your directory is empty.

So, first you delete the files (which you already have done), and then you can start using rmdir for deleting the directories, but beware: you need to do this from inside to outside (from the deepest subsubsub...directory back to the main directory).

CodePudding user response:

The standard FOR command only iterates files. So you need a mechanism to list file and folders at the same time. You also need a mechanism to determine if the object iterated is a file or folder so that you use the correct command to either delete the file or remove the directory.

@echo off
CD /D "C:\root folder"
for /F "delims=" %%G in ('dir /b') do (
    REM check if it is a directory or file
    IF EXIST "%%G\" (
        rmdir "%%G" /s /q
    ) else (
        del "%%G" /q
    )
)
  • Related