batch-filewindows-10xcopytaskschedulerwmic

Batch file using WMIC not working correctly with TaskScheduler (but working fine from command line!)


I decided to write a small batchfile to make daily copies of a folder and its contents. I used WMIC to properly format the date in order to name the folders automatically. While it works perfectly on the command line, it seems that it dislikes being executed by the TaskScheduler - it does make a copy of the folder, but doesn't retrieving any date, and saves the files into a folder named -~-2-~-2. It seems to skip the first part of the code altogether, and jump directly to the Pad digits part, from where it gets the ~-2 bit. Any suggestions would be most welcome!

Here's my batch file:

@Echo off
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Month^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%

:: Display the date/time in ISO 8601 format:
Set _date=%_yyyy%-%_mm%-%_dd%
Echo %_date%

:: Xcopy the files!

xcopy /s /i "C:\Users\Alcides\Documents\CQC_APS_TESE_DOUTORAMENTO_LaTeX" "I:\Tese-Backup\"%_date%\

GOTO:EOF

:s_error
Echo GetDate.cmd
Echo Displays date and time independent of OS Locale, Language or date format.
Echo:
Echo Returns 6 environment variables containing isodate,Year,Month,Day,hour and minute.

Solution

  • I would suggest you use a quicker method for determining your date than .

    The following example uses :

    @Set "_date="
    @For /F "Tokens=1-3Delims=/ " %%A In ('^""%__AppDir__%RoboCopy.exe" /NJH /L "\|" Null^"')Do @If Not Defined _date Set "_date=%%A-%%B-%%C"
    @"%__AppDir__%XCopy.exe" "C:\Users\Alcides\Documents\CQC_APS_TESE_DOUTORAMENTO_LaTeX" "I:\Tese-Backup\%_date%\" /S