Nikunj Parikh
Nikunj Parikh

Reputation: 23

How to delete all the folder except one folder and its content using command prompt?

Say for example I have a folder abc containing sub folders 1, 2, 3, 4. Now I want to delete all the folders except folder 2 and its content. I have tried

PUSHD (c:\abc\2) 
rd /s /q "C:\abc" 2>nul

But it deletes the files inside the 2 folder also. I don't want any of the files of folder 2 deleted?

Upvotes: 2

Views: 1789

Answers (1)

aschipfl
aschipfl

Reputation: 34909

The following code should work:

for /D %%D in ("C:\abc\*.*") do (
    if /I not "%%~nxD"=="2" (
        2> nul rd /S /Q "%%~fD"
    )
)

The for /D loop walks through the directories 1, 2, 3, 4.
The if statement checks the name of the currently iterated directory not to be 2.

Upvotes: 3

Related Questions