问题
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.
回答1:
I would suggest you use a quicker method for determining your date than wmic.
The following example uses robocopy:
@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
回答2:
If you want to get ISODate
from WMIC
, you should try something like this code :
@echo off
Title GET ISODATE FROM WMIC
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%
echo Today : %today%
set "year=%MyDate:~2,2%"
set "month=%MyDate:~4,2%"
set "day=%MyDate:~6,2%"
echo %day%%month%%year%
pause
来源:https://stackoverflow.com/questions/58589554/batch-file-using-wmic-not-working-correctly-with-taskscheduler-but-working-fine