Delete all folders except one

10,938

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.

Share:
10,938
Romain
Author by

Romain

Updated on June 04, 2022

Comments

  • Romain
    Romain almost 2 years

    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?