Find and Copy files to New folder

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gurwinder.singh
Posts: 1
Joined: 22 Jul 2021 09:49

Find and Copy files to New folder

#1 Post by gurwinder.singh » 22 Jul 2021 09:54

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


atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: Find and Copy files to New folder

#2 Post by atfon » 22 Jul 2021 11:41

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.

Post Reply