Delete all folders except one

Romain picture Romain · Sep 2, 2016 · Viewed 10.1k times · Source

I want to delete all files and folders in my C:\temp except one specific folder (C:\temp\123) which contains a lot of files and subfolders.

I tried with pushd "c:\temp\123" && rd /s /q "c:\temp" but it deletes all subfolders and files in c:\temp\123

Can any one please help on the above?

Answer

aschipfl picture aschipfl · Sep 2, 2016

You could do it the following way:

pushd "C:\Temp" || exit /B 1
for /D %%D in ("*") do (
    if /I not "%%~nxD"=="123" rd /S /Q "%%~D"
)
for %%F in ("*") do (
    del "%%~F"
)
popd

This is very similar to this approach: Batch command to delete everything (sub folders and files) from a folder except one file.