0

Lately i have been making this batch file and it is driving me nuts.

My Folder Structure is like C:\MainFolder\Dir\ and "Dir" contains many sub Folders and Files. Within these Sub Folders there are many files and sub Folders including 2 files "C.txt" and "D.txt" My Task is to delete everything else in these sub folders and only keep these 2 files. But it is not working. Please Help.

My Code is :

@echo off
FOR /f "tokens=*" %%M in ('dir /b "C:\MainFolder\Dir\"') DO (
For /f "tokens=*" %%S in ('dir /b "C:\MainFolder\Dir\%%M"') DO ( 
if "%%S"=="C.txt" ( 
echo Found C
) 
else if "%%S"=="D.txt" ( 
echo Found D
) 
else (
::Code to delete the file Or Directory
echo Deleted %%S
)

)
)
echo Deleted Unwanted Content
pause

1 Answer 1

1

There are multiple problems here:

The else has to appear on the same line as the (:

if "%%S"=="C.txt" ( 
  echo Found C
) else if "%%S"=="D.txt" ( 
  echo Found D
) else (
  ::Code to delete the file Or Directory
  echo Deleted %%S
)

Do not use :: for comments, it breaks in certain places. Use rem instead:

) else (
  REM Code to delete the file Or Directory
  echo Deleted %%S
)

And please indent your code. It makes reading it much more pleasant:

@echo off
FOR /f "tokens=*" %%M in ('dir /b "C:\MainFolder\Dir\"') DO (
  For /f "tokens=*" %%S in ('dir /b "C:\MainFolder\Dir\%%M"') DO ( 
    if "%%S"=="C.txt" ( 
      echo Found C
    ) else if "%%S"=="D.txt" ( 
      echo Found D
    ) else (
      REM Code to delete the file Or Directory
      echo Deleted %%S
    )
  )
)
echo Deleted Unwanted Content
pause
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Worked for me. Here's my Working Code: @echo off set /p path= enter absolute/relative Path upto root Folder FOR /f "tokens=*" %%M in ('dir /b "%path%\"') DO ( For /f "tokens=*" %%S in ('dir /b "%path%\%%M"') DO ( if "%%S"=="web.config" ( echo Found web.config ) else if "%%S"=="web.bak" ( echo Found web.bak ) else ( rmdir /s /q "%path%\%%M\%%S" del /f "%path%\%%M\%%S" echo Deleted %%S ) ) ) echo Deleted All Unwanted Content pause

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.