1
votes

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

  • folder1/file1.txt
  • folder2/file1.txt
  • keep1/file1.txt
  • keep2/file1.txt
  • file1.txt

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.

2
I've just tried your code and it did not removed the files from folder keep1 and keep2, so it looks like it's working fine.Emil Borconi
Did you use the same file in all folders and root? If I put different files, it works fine. If I use same files, it deletes them all.CZFox
I used the same (empty) file all over the place.Emil Borconi
You can't use the /S option with the DELETE command. That means to delete the file from the current directory and all subdirectories.Squashman

2 Answers

1
votes

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
            )
        )
    )
)
0
votes

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