RishiKesh Pathak
RishiKesh Pathak

Reputation: 2282

How to delete all files and directories with an exception

I have a few files and directories, (all directories contain files):

C:\ABC
│   file1.txt
│
├───folder1
│       oneormorefiles.ext
│
├───folder2
│       somemorefiles.ext
│
└───logs
        aaa-test-01.log
        b-test-a-02.log
        cc-test-03.log

I want to delete all of the directories and the files they contain, but wish to keep C:\abc\logs and all of its files.

I have tried:

PUSHD "c:\logs" && rd /s/q "c:\abc" 2>nul

but this is deleting files in C:\abc\logs as well, (I want to avoid that).

Thanks

Upvotes: 3

Views: 3282

Answers (2)

Compo
Compo

Reputation: 38719

I would suggest this as a possibile alternative to using FOR loop and/or a mixture of DEL and RD:

MD "%TEMP%\$_.dummy"&&ROBOCOPY "%TEMP%\$_.dummy" "C:\abc" /E /XD logs /PURGE>NUL 2>&1&RD "%TEMP%\$_.dummy"

Upvotes: 4

aschipfl
aschipfl

Reputation: 34989

I would do it the following way:

rem // Change to the target root directory:
pushd "C:\ABC" && (
    rem // Loop over all immediate sub-directories:
    for /F "delims= eol=|" %%F in ('dir /B /A:D "*"') do (
        rem // Remove sub-directory tree unless name is `log`:
        if /I not "%%F" == "logs" rd /S /Q "%%F"
    )
    rem // Delete files located in the root directory:
    del /A /F /Q "*.*"
    rem // return to the original directory:
    popd
)

Upvotes: 1

Related Questions