Page 1 of 1

Find and Copy files to New folder

Posted: 22 Jul 2021 09:54
by gurwinder.singh
Hey Guys,

I have been toying with this for a week searching boards and stack overflow. I got it to work on move over 1200 files then it stopped working. Can someone please help?

Code: Select all

echo @on

setlocal EnableExtensions EnableDelayedExpansion

set "SourceBaseFolder=G:\EO\Catalog \Photography\Frames"
set "TargetBaseFolder=C:\Users\%USERNAME"\Desktop\New folder"


if not exist "%SourceBaseFolder%\*" (
    echo %~nx0: There is no folder %SourceBaseFolder%
    set "ErrorCount=1"
    goto HaltOnError
)

cd /D "%SourceBaseFolder%"

if not exist "FileNames.txt" (
    echo %~nx0: There is no file %SourceBaseFolder%\FileNames.txt
    set "ErrorCount=1"
    goto HaltOnError
)

set "ErrorCount=0"
for /F "usebackq delims=" %%N in ("FileNames.txt") do (
    for /R %%J in ("%%N*") do (
        set "FilePath=%%~dpJ"
        if "!FilePath:%TargetBaseFolder%=!" == "!FilePath!" (
            set "TargetPath=%TargetBaseFolder%\Copy"
            md "!TargetPath!" 2>nul
            if exist "!TargetPath!\*" (
                echo Copying file %%~fJ
                copy /Y "%%~fJ" "!TargetPath!" >nul
            ) else (
                set /A ErrorCount+=1
                echo Failed to create directory !TargetPath!
            )
        )
    )
)

:HaltOnError
if %ErrorCount% NEQ 0 (
    echo.
    pause
)
endlocal


Re: Find and Copy files to New folder

Posted: 22 Jul 2021 11:41
by atfon
Just one quick tip. You are missing the closing % in username for the target location. An easier way to set the target folder would be:

Code: Select all

set "TargetBaseFolder=%userprofile%\Desktop\New folder"
The environment variable %userprofile% will typically expand to "C:\Users\<username>"

You can type

Code: Select all

echo %userprofile%
in the COMSPEC too see what it expands to on your system.