mribraqdbra
mribraqdbra

Reputation: 35

batch - if folders contains the specific sub folder move it

Problem: It's only moves one folder "FolderB.tag" to "GoodFolder"

Question: How to make It moves all folders to another by following the rules

myscript.bat

@echo off
md GoodFolder
md BadFolder
for /d %%i in (*.tag) do set check=%%i
if exist "%check%\SubFolderA" (move "%check%" "GoodFolder")
if not exist "%check%\SubFolderA" (move "%check%" "BadFolder")
pause
exit /b

mydirectory

BadFolder
GoodFolder
+---Folder C.tag
|   +---SubFolderA
|   \---SubFolderB

+---FolderA.tag
|   \---SubFolderB

+---FolderB.tag
|   \---SubFolderA

Upvotes: 0

Views: 55

Answers (2)

Michael Mantion
Michael Mantion

Reputation: 215

EnableDelayedExpansion does solve your problem but I typically like calling subroutines when dealing with for loops. Both solutions should solve your issue.

@Echo Off
MD GoodFolder 2>NUL
MD BadFolder 2>NUL
For /D %%I In (*.tag) Do Call :Sorting "%%I"
Pause
Exit /B

:Sorting
If Exist "%~1\SubFolderA\" (
     Echo moving %1 to GoodFolder
     Move "%*" "GoodFolder"
) Else (
     Echo moving %1 to BadFolder
     Move "%~1" "BadFolder"
)
GoTo :EOF

Upvotes: 0

Compo
Compo

Reputation: 38613

As a follow-on from my comment, what you needed to do was to include your if commands within the do portion of the for loop.

Example as requested:

@Echo Off
MD GoodFolder 2>NUL
MD BadFolder 2>NUL
For /D %%I In (*.tag) Do (
    If Exist "%%I\SubFolderA\" (
        Move "%%I" "GoodFolder"
    ) Else Move "%%I" "BadFolder"
)
Pause
Exit /B

You'll note that I did not include the setting of a variable unnecessarily. Had you needed to do that, for some other purpose, then you'd need to have delayed the expansion of that variable in order to effectively use it.

Example:

@Echo Off
MD GoodFolder 2>NUL
MD BadFolder 2>NUL
For /D %%I In (*.tag) Do (
    Set "check=%%I"
    SetLocal EnableDelayedExpansion
    If Exist "!check!\SubFolderA\" (
        Move "!check!" "GoodFolder"
    ) Else Move "!check!" "BadFolder"
    EndLocal
)
Pause
Exit /B

Upvotes: 1

Related Questions