Search code examples
windowsbatch-filecmd

Batch file fails to consistently create log file


I have a batch file that creates a log file with the date and time appended to the filename. This batch file is set to run a series of tasks every morning through Windows Task Scheduler. Every morning when the script runs, the batch file will only partially name the log file. It should be named report_log_2020-12-10_03-00-00.log, but the time doesn't always get added, resulting in report_log_2020-12-10_ (so it's not even a .log file, but a file with no extension).

When I manually run the batch script, the file is created properly. The file is also created properly when I manually run the task under Windows Task Scheduler. However, when the task runs in the mornings on it's own, that is when the time and .log is left off of the filename. This is a very odd behavior that has me baffled. Below is the code I am using.

::Created: 08/18/20
::Updated: 12/09/20

@ECHO OFF

::Set date/time
SET LOGFILE=Logs\report_log_%date:~-4,4%-%date:~-10,2%-%date:~-7,2%_%time:~0,2%-%time:~3,2%-%time:~6,2%.log
CALL :LOG >> %LOGFILE%
EXIT /B

:LOG

::Begin script
ECHO %date% %time%: ##### Refresh Begins #####

::Run Alteryx workflow
ECHO %date% %time%: Running Alteryx workflow...
CALL "C:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "C:\Users\filepath\Workflow.yxmd"

::Replace Error Checking Files
ECHO %date% %time%: Replacing error checking file...
DEL "C:\Users\filepath\Error Check - Previous.xlsx"
RENAME "C:\Users\filepath\Error Check - New.xlsx" "Error Check - Previous.xlsx"

::Check for log file
ECHO %date% %time%: Checking if Oracle log exists...
PowerShell.exe -Command "& 'C:\Users\filepath\log_check.ps1'"

::End script
ECHO %date% %time%: ##### Refresh Complete #####

::PAUSE

::Finish

Solution

  • After

    SET LOGFILE=Logs\report_log_%date:~-4,4%-%date:~-10,2%-%date:~-7,2%_%time:~0,2%-%time:~3,2%-%time:~6,2%.log
    

    add

    SET "LOGFILE=%logfile: =0%"
    

    The time and date formats are user-dependent, and may vary according to the user under which the process runs. Consequently, the time may contain a leading space for hours, so the filename is truncated at the space.