CrazyCoder
CrazyCoder

Reputation: 2378

Remove only files and sub folders from a directory through command prompt

I have a folder named Test in C:\Test path. There are multiple files and folders in this Test folder. Now I want to remove all the contents with in the Test Folder and not delete the Test folder itself.

I have been trying these commands, but it only deletes the files and not folders.

del C:\Test\* 
del C:\Test\*.*

I want a single command to delete both files and sub folders from Test.

Upvotes: 0

Views: 2638

Answers (2)

aschipfl
aschipfl

Reputation: 34909

It is not possible with a single command, but with a single command line.

I would do this:

cd /D "C:\Test" && rd /S /Q "C:\Test"

This first changes into the destination root directory. The && operator lets the following command execute only when the preceding one succeeded. Then the directory and all its contents is attempted to be deleted; for the contents it works fine, but for the root itself, the error The process cannot access the file because it is being used by another process. because of the preceding cd command. This error message (and also others) can be suppressed by appending 2> nul to the rd command:

cd /D "C:\Test" && rd /S /Q "C:\Test" 2> nul

If you want the original working directory to be restored, use pushd/popd rather than cd:

pushd "C:\Test" && (rd /S /Q "C:\Test" 2> nul & popd)

The advantage of this method over deletion and recreation (like rd /S /Q "C:\test" && md "C:\Test") is that the attributes, the owner and the security settings of the root directory are not lost.


Alternatively, you could do the following, which is more complicated but avoids suppression of errors:

del /S /Q "C:\Test\*.*" & for /D %%D in ("C:\Test\*") do @rm /S /Q "%%~D"

This first deletes all files that reside in the root directory, then it loops through all immediate sub-directories and deletes one after another. The root directory itself is never touched.

Upvotes: 2

CrazyCoder
CrazyCoder

Reputation: 2378

This is the command which has to be used.

CD "C:/Test" && FOR /D %i IN ("*") DO RD /S /Q "%i" && DEL /Q *.* 

Upvotes: 1

Related Questions