Search code examples
batch-filedirectorycopyxcopy

Xcopy Script for Changing Directory


I'm currently trying to come up with a script to copy several files from one location to the operating location of a program and then launching the application. Currently I have this:

xcopy /s /v /z "I:\test\20150520\Files\stmt" "C:\Users\test\Desktop\test2"
PAUSE
START C:\Windows\NOTEPAD.EXE

This script seems to work without a problem but the issue I'm running into is that my from directory changes each day where I have 20150520. The directory's below that are always the same its just the one changes daily and I would need the script to do that as well.

Is there anyway that this can be done?


Solution

  • Next script expects a valid parameter (see %~1 in the code and example provided below); if a parameter not found or does not match a valid folder then gets today's date (see the :getToday subroutine).

    @ECHO OFF >NUL
    SETLOCAL enableextensions
    set "dayFolder=%~1"
    if "%dayFolder%"==""                           call :getToday
    if not exist "I:\test\%dayFolder%\Files\stmt\" call :getToday
    
    if exist "I:\test\%dayFolder%\Files\stmt\" (
        xcopy /s /v /z "I:\test\%dayFolder%\Files\stmt" "C:\Users\test\Desktop\test2"
    ) else (
        echo invalid "%~1" parameter or "%dayFolder%" folder does not exist
    )
    PAUSE
    START C:\Windows\NOTEPAD.EXE
    
    goto :eof
    :getToday
    for /F "tokens=2 delims==" %%G in (
        'wmic OS get LocalDateTime /value'
    ) do @for /F "tokens=*" %%x in ("%%G") do (
        set "dayFolder=%%~x"
    )
    set "dayFolder=%dayFolder:~0,8%"
    goto :eof
    

    Here the for loops in the :getToday subroutine are

    • %%G to retrieve the LocalDateTime value;
    • %%x to remove the ending carriage return in the value returned (wmic behaviour: each output line ends with 0x0D0D0A instead of common 0x0D0A).

    Output:

    ==>D:\bat\StackOverflow\30356205.bat
    invalid "" parameter or "20150521" folder does not exist
    Press any key to continue . . .
    
    ==>D:\bat\StackOverflow\30356205.bat 2015 05 19
    invalid "2015" parameter or "20150521" folder does not exist
    Press any key to continue . . .