Search code examples
batch-filecopy

Batch file - Root folder does not copy


1: The following code creates a date stamped destination folder correctly, ie:

\\MyServer\MyFiles\Version\YYYMMDDHHNN\

2: However, only files from the source are copied over, not the folder. What I get is:

\\MyServer\MyFiles\Version\YYYMMDDHHNN\Myfile01.txt
\\MyServer\MyFiles\Version\YYYMMDDHHNN\Myfile02.txt

What I want to achieve is:

\\MyServer\MyFiles\Version\YYYMMDDHHNN\MyFolderToCopy\Myfile01.txt
\\MyServer\MyFiles\Version\YYYMMDDHHNN\MyFolderToCopy\Myfile02.txt

What am I doing wrong?

Note: I cannot specify the SOURCE as C:\Users\123456\ as there may be other folders in this path that I do not wish to copy.

Thanks in advance for any help!


SET SOURCE="C:\Users\123456\MyFolderToCopy\\"
SET DESTINATION="\\MyServer\MyFiles\Version\\"

REM - CREATE DATE STAMP FOR FOLDER:
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
SET YYYY=%dt:~0,4%
SET MM=%dt:~4,2%
SET DD=%dt:~6,2%
SET HH=%dt:~8,2%
SET Min=%dt:~10,2%

SET STAMP=%YYYY%%MM%%DD%%HH%%Min%
SET NEW_FOLDER=%DESTINATION%%STAMP%
MKDIR %NEW_FOLDER%
XCOPY %SOURCE% %NEW_FOLDER% /E

Solution

  • At the beginning there's two backslashes in your Code for source so that could be omitted but maybe that's just a copy pasta mistake in this threat.

    SET SOURCE="C:\Users\123456\MyFolderToCopy"
    

    As for XCOPY try the additional /I switch:

    XCOPY %SOURCE% %NEW_FOLDER%\MyFolderToCopy /E /I
    

    This command ensures that the root folder MyFolderToCopy is also copied into the NEW_FOLDER. The /I switch forces XCOPY to treat the destination as a directory.

    You can also use

    pause
    

    at the end, to see if there are any messages before the window closes.