0

Hello! I am trying to make a batch file that when dropped to any parent folder, it will grab all the content of said folder and creates a sub-folder called "Sorted Files" where other sub-folders will be created based on the file's extension, then moved to the according folder. If there's a file with the same name, it will be renamed with enumeration.

ex: Cool_Beans.jpeg, Cool_Beans(1).jpeg, Cool_Beans.jpeg(2), and so on.

I made it work for .jpeg files, but then I edited the code to base on a variable's extension; everything gets moved to the Parent folder (Current Directory), and the duplicates are now being overwritten.

Here is what I have so far:

@ECHO OFF
@setlocal enableextensions enabledelayedexpansion

REM Existence Check
If not exist "%cd%\Sorted Files" (mkdir "Sorted Files")

REM Declare Source
set "source=%cd%"

REM Organizer
FOR /R "%source%" %%i in (*.*) do ( 
    REM Destination
    set "target=%cd%\Sorted Files\%%~xi"
    if not exist "%target%" (mkdir "%target%")
    REM Move
    If not exist "%target%\%%~nxi" (move "%%i" "%target%") ELSE (call :index "%%~i" "%target%\%%~nxi" "1")
)

REM Call
:index  source, target, count

REM Counter
setlocal
set /a "cnt=%~3"

if exist "%target%\%~n2(%cnt%)%~x2" (
    call :index "%~1" "%~2" "%cnt%+1"
) else move "%~1" "%target%\%~n2(%cnt%)%~x2"

My question is, how can I make it so the files inside a parent folder and its sub-folders are moved to their designated folders inside "Sorted Files"?, the designated folder being a sub-folder generated and named according to the file's extension.

My goal is to make this little batch to organize several computers and backups, hopefully adding more code in the future to delete the leftover empty folders and moving files too long to rename to an "Overflow" folder.

Durry42
  • 401
  • 3
  • 10
  • Avoid using `%CD%` as this can sometimes contain the wrong path (Depending on how you run it) Instead use `%~dp0` (this will include a trailing slash in output). **Example** Create a file with lines... `@echo off` `echo CD:%CD%` `echo DP:%~dp0` `pause` Then run it by double-click...next run it by calling it from another location. The %~dp0` will always reference the path the script itself is located in. – Durry42 Mar 10 '20 at 01:38
  • You have `setlocal enabledelayedexpansion` yet you set `target` and use `%target%` in the same read code block. `%target%` will be undefined as it is not set before the loop starts. Use `!target!` instead, which is using delayed expansion. – michael_heath Mar 10 '20 at 09:23
  • 1
    Thank you kindly, both of you. I took Durry42's advice and replaced %cd% to %~dp0 to avoid some minor issues if the batch was ran again. Then, michael_health's lesson really helped find the issue. After some trial and error, I've managed to get the hand of delayed expansion variables. Batch is running like a charm! – Josue J. Gerena Gerena Mar 10 '20 at 23:41

0 Answers0