I have a Scheduled Task which runs, every 15 minutes, a very very quick BATCH process. This first "FILE1.bat" process calls another one like this: "FILE2.bat" >> PATH\winscp_TODAYSDATE.txt This way I can get all the output from the second into a TXT "log file". FILE2.bat just copies files to a "DONE" folder and sends them via WINSCP to a provider, with a mput -delete, which deletes the files once successfully sent.
For some reason unknown to me, the TASK (not sure if the task itself, the FILE1 or the FILE2) runs twice (even thrice), one immediatly after another just by some miliseconds, as shown in the next text. This is the result when there are no files to be processed:
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 0:05:01,26 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 0:05:01,77 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 0:20:00,97 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 0:20:01,26 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 0:20:01,76 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
But when there are files to be processed, this happens (not always, though):
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 14:05:01,47 ********
*************************************************************
***** Se comprueba si hay ficheros TXT que existan para procesar: SI
***** Se copian los ficheros que existan para enviar antes de enviarlos a la subcarpeta COPIAS, sobreescribiendo
l:\entradas\ALS20221221135146008008649.txt
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 14:05:02,47 ********
*************************************************************
***** Se comprueba si hay ficheros TXT que existan para procesar: SI
***** Se copian los ficheros que existan para enviar antes de enviarlos a la subcarpeta COPIAS, sobreescribiendo
l:\entradas\ALS20221221135146008008649.txt
l:\entradas\ALS20221221135434008008649.txt
l:\entradas\ALS20221221135534008008649.txt
l:\entradas\ALS20221221135809008008649.txt
4 archivo(s) copiado(s).
***** Se ejecuta WINSCP con los parametros necesarios
Connecting to x-x-x-x-x-x-x-x-x-xguro.com ...
Connected
Starting the session...
Session started.
Active session: [1] copx-x-x-xx-x-x-x-x-x-x-x-x-xguro.com
l:\entradas
/ENTRADAS
ALS20221221135146008008649.txt | 14 KB | 0,0 KB/s | binary | 100%
ALS20221221135434008008649.txt | 1 KB | 5,6 KB/s | binary | 100%
ALS20221221135534008008649.txt | 1 KB | 6,2 KB/s | binary | 100%
ALS20221221135809008008649.txt | 1 KB | 6,8 KB/s | binary | 100%
/SALIDAS
l:\SALIDAS
No file matching '*' found.
Session 'copx-x-x-xx-x-x-x-x-x-x-x-x-xguro.com' closed.
No session.
***** Se revisa si ha habido errores en el envio. ERRORCODE:0
***** Envio sin errores: Se omite el email
***** Resultado del envio por FTP
Success - The files were uploaded successfully. - FICHEROS ENVIADOS: SI
*************************************************************
******** HORA DEL REGISTRO: 21/12/2022 - 14:20:01,88 ********
*************************************************************
***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
Success - No files to process - FICHEROS ENVIADOS: NO FILES
The files are successfully sent, fortunately and so far, but it fills the log and I'm not at ease about it...
I have looked as hard as I could, unable to find reason or solution to this behavior. I am attaching, too, the XML of the exported TASK.
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2022-10-28T12:14:19.6597722</Date>
<Author>SEFRISA\eqm</Author>
<URI>\_GyV FTP Logifrio_</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT15M</Interval>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2022-10-28T12:05:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-1834156839-169156998-926709054-1284</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>GyV_Reg.bat</Command>
<WorkingDirectory>C:\TareasFTP_Logifrio\</WorkingDirectory>
</Exec>
</Actions>
</Task>
I just looked for a solution and tried changing the task options, but none worked and even some of the options were disabling the proper execution of the task.
EDIT:
@Mofi, here you have FILE1 (GyV_Reg.bat) and FILE2 (gyv.bat). I believe I tried, at some point, running the task as you mention, with %SystemRoot%\System32\cmd.exe
, but unsuccessfully. I'll investigate more about the /D /C modifiers. Thank you very much
Gyv_Reg.bat
@echo off
if not exist l: net use l: /persistent:yes \\servidor2k9\logifrio$
set day=%date:~0,2%
set month=%date:~3,2%
set year=%date:~6,4%
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set FECHA_HOY=%year%%month%%day%
gyv.bat >> L:\WinScpLogs\winscp_%FECHA_HOY%.txt
gyv.bat (without any sensitive information)
@echo off
REM setlocal enabledelayedexpansion
ECHO *************************************************************
ECHO ******** HORA DEL REGISTRO: %DATE% - %TIME% ********
ECHO *************************************************************
if not exist l: (
net use l: /persistent:yes \\servidor2k9\logifrio$
ECHO ***** No existe la unidad L: Se mapea como persistente
)
rem ECHO ***** Se accede a la unidad L:
l:
REM Se comprueba si hay ficheros TXT que existan para enviar
if not exist l:\entradas\AL*.TXT (
set FILES_EXIST=NO
set FILES_SENT=NO FILES
set WINSCP_SUBJECT=Success
set WINSCP_MESSAGE=No files to process
REM Si no hay ficheros TXT para procesar, se omite el proceso
GOTO SkipProcess
)
REM Se especifican la ruta y el formato del nombre del fichero de LOGS
set FILES_EXIST=SI
set day=%date:~0,2%
set month=%date:~3,2%
set year=%date:~6,4%
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set FECHAHORA=%year%%month%%day%-%hour%%min%
set WINSCP_LOG_HOY=L:\WinScpLogs\winscp_%FECHAHORA%.xml
ECHO ***** Se comprueba si hay ficheros TXT que existan para procesar: %FILES_EXIST%
ECHO ***** Se copian los ficheros que existan para enviar antes de enviarlos a la subcarpeta COPIAS, sobreescribiendo
copy l:\entradas\*.* l:\entradas\copias /y
ECHO ***** Se ejecuta WINSCP con los parametros necesarios
REM ******************************************************************************************************************
REM La linea siguiente, COMENTADA, se puede habilitar, inhabilitando la de debajo, para hacer pruebas sin enviar nada
REM ******************************************************************************************************************
rem c:\winscp.com /ini=nul /script="C:\TareasFTP_Logifrio\gyv_test.txt" /log=%WINSCP_LOG_HOY% /xmlgroups /loglevel=2 /logsize=20*1M
REM ******************************************************************************************************************
c:\winscp.com /ini=nul /script="C:\TareasFTP_Logifrio\gyv.txt" /log=%WINSCP_LOG_HOY% /xmlgroups /loglevel=2 /logsize=20*1M
set ERROR_CODE=%ERRORLEVEL%
ECHO ***** Se revisa si ha habido errores en el envio. ERRORCODE:%ERROR_CODE%
IF %ERROR_CODE% NEQ 0 (
ECHO ***** Envio con errores: Se prepara el email
set WINSCP_SUBJECT=Error FTP Logifrio-SRVIMPRESORAS
set WINSCP_MESSAGE=Error uploading files, see attached log. ErrorLevel: %ERROR_CODE%
ECHO ********** WINSCP_MESSAGE: %WINSCP_MESSAGE%
REM Prepare email contents
set SMTP_FROM=siX-X-X-X-X-X@X-X-X-X-X-X.com
set SMTP_TO=siX-X-X-X-X-X@X-X-X-X-X-X.com
set SMTP_SERVER=smtpX-X-X-X-X-X.com
set SMTP_USERNAME=siX-X-X-X-X-X@X-X-X-X-X-X.com
set SMTP_PASSWORD=CoX-X-X-X-X-X3
REM Check if LOG file exists and set it as attachment for the email
if exist %WINSCP_LOG_HOY% (
ECHO ********** WINSCP_LOG_HOY: %WINSCP_LOG_HOY%
set ATTACHMENT=%WINSCP_LOG_HOY%
) else (
ECHO ***** No existe WINSCP_LOG_HOY - Se genera uno vacio en TXT
set WINSCP_LOG_VACIO=C:\TareasFTP_Logifrio\winscp_VACIO_%FECHAHORA%.txt
ECHO NO EXISTE LOG > "%WINSCP_LOG_VACIO%"
set ATTACHMENT=%WINSCP_LOG_VACIO%
)
set FILES_SENT=NO
GOTO SendEmail
) else (
ECHO ***** Envio sin errores: Se omite el email
set WINSCP_SUBJECT=Success
set WINSCP_MESSAGE=The files were uploaded successfully.
set FILES_SENT=SI
GOTO Resultado
)
:SendEmail
ECHO ***** Envio del email a siX-X-X-X-X-X@X-X-X-X-X-X.com
REM Send the email message
CALL :PowerShell
CD /D "%PowerShellDir%"
ECHO '%PSScript%' '%SMTP_USERNAME%' '%SMTP_PASSWORD%' '%ATTACHMENT%'
Powershell.exe -ExecutionPolicy Bypass -Command "& '%PSScript%' '%SMTP_USERNAME%' '%SMTP_PASSWORD%' '%ATTACHMENT%'"
CD /D "C:\TareasFTP_Logifrio"
:Resultado
ECHO ***** Resultado del envio por FTP
ECHO %WINSCP_SUBJECT% - %WINSCP_MESSAGE% - FICHEROS ENVIADOS: %FILES_SENT%
GOTO FIN
:SkipProcess
ECHO ***** SIN ficheros TXT para procesar, se ha omitido el proceso y no se envia email
ECHO %WINSCP_SUBJECT% - %WINSCP_MESSAGE% - FICHEROS ENVIADOS: %FILES_SENT%
GOTO FIN
:FIN
rem ECHO ***** Se vuelve a acceder a la unidad C:
c:
GOTO SALIR
:PowerShell
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
SET PSScript=%temp%\~tmpSendeMail.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
ECHO $Username = "%SMTP_USERNAME%" >> "%PSScript%"
ECHO $EmailPassword = "%SMTP_PASSWORD%" >> "%PSScript%"
ECHO $Attachment = "%ATTACHMENT%" >> "%PSScript%"
ECHO >> "%PSScript%"
ECHO $Username = "%SMTP_USERNAME%" >> "%PSScript%"
ECHO $EmailTo = "%SMTP_TO%" >> "%PSScript%"
ECHO $EmailFrom = "%SMTP_FROM%" >> "%PSScript%"
ECHO $Subject = "%WINSCP_SUBJECT%" >> "%PSScript%"
ECHO $Body = "%WINSCP_MESSAGE%" >> "%PSScript%"
ECHO $SMTPServer = "%SMTP_SERVER%" >> "%PSScript%"
ECHO $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body) >> "%PSScript%"
ECHO $Attachment = New-Object System.Net.Mail.Attachment($Attachment) >> "%PSScript%"
ECHO $SMTPMessage.Attachments.Add($Attachment) >> "%PSScript%"
ECHO $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) >> "%PSScript%"
ECHO $SMTPClient.EnableSsl = $true >> "%PSScript%"
ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword) >> "%PSScript%"
ECHO $SMTPClient.Send($SMTPMessage) >> "%PSScript%"
GOTO :EOF
:SALIR
@echo on