CZFox
CZFox

Reputation: 9285

Delete all except two folders with .bat file

Batch

@echo off
set folder="c:\FTP\"
set keep="keep1"
set keeptwo="keep2"

cd /d %folder%

for /F "delims=" %%i in ('dir /b') do (
    if /i "%%~ni" NEQ %keep% if /i "%%~ni" NEQ %keeptwo% (rmdir "%%i" /s/q || del "%%i" /s/q)
)

pause

Situation

Expected result

I need to keep "keep1" and "keep2" folders and all included files, but "folder1" and "folder2" and "file1.txt" with all subdirectories and files must be deleted.

Current result

It removes all files in all folders, removes "folder1" and "folder2", and keeps "keep1" and "keep2"

Any clue what I'm missing.

Upvotes: 2

Views: 1207

Answers (2)

Compo
Compo

Reputation: 38719

I'm assuming that this is what you wanted to do:

@Echo Off
Set "folder=C:\FTP"
Set "keep=keep1"
Set "keeptwo=keep2"

CD /D "%folder%" 2>Nul || Exit /B
Del /F/A/Q *
For /D %%A In (*) Do If /I Not "%%A"=="%keep%" If /I Not "%%A"=="%keep2%" RD /S/Q "%%A"
Pause

Upvotes: 0

Squashman
Squashman

Reputation: 14340

You cannot use the /S option with the DELETE command as that will delete the file in the current directory and all subdirectories.

Regardless of that, this is how I would accomplish the task so that you don't get the error from the RMDIR command. I use an IF EXIST command to determine if it is a file or directory.

@echo off
set "folder=c:\FTP\"
set "keep=keep1"
set "keeptwo=keep2"

cd /d %folder%

for /F "delims=" %%G in ('dir /b') do (
    if /I NOT "%%G"=="%keep%" (
        if /I NOT "%%G"=="%keeptwo%" (
            REM check if it is a directory or file
            IF EXIST "%%G\" (
                rmdir "%%G" /s /q
            ) else (
                del "%%G" /q
            )
        )
    )
)

Upvotes: 3

Related Questions