A batch file executes WinSCP.exe's console mode to download files and log the actions. Upon exit, WinSCP returns:
ERRORLEVEL 0
if the files are successfully retrieved orERRORLEVEL 1
if there is a problem with the connection - time outs, etc. - or if no file is found- Unexplainably, WinSCP will occasionally return
0
when no files are found
Due to this, to meet audit requirements, I must check for four possibilities:
ERRORLEVEL 1
and a connection problemERRORLEVEL 0
and the file(s) exist(s)ERRORLEVEL 1
orERRORLEVEL 0
and no file found
And respond with one of three options (respectively):
- Send email indicating error
- Send email indicating success
- Send email indicating no file
Note, the same group who receives the success notice, should also receive the no file notice as that is not download failure. The code reflects this.
I wrote the fully functional code below but am not sure it's as streamlined as it could be. My first concern is that I can improve flow by using GOTO
and perhaps CALL
or :EOF
commands in more appropriate ways as I can't seem to find a better 'structure' for the conditions/responses. My goal is to eliminate un-necessary spaghetti-ing. Second, I am troubled to find a better way to reset the ERRORLEVEL
to zero so I can use an ERRORLEVEL
check twice (currently the %comspec%...
line). I'm not even sure I need two checks. I appreciate all suggestions.
The code I'm concerned with begins the line after START /WAIT...
but I present it in full, for reference:
SET [email protected]
SET [email protected]
SET [email protected]
SET MailSrcName=Automated FTP Process
SET OKMailSub=Files Have Been Moved
SET NoFileMailSub=Files Not Present - Maybe Next Time
SET FailMailSub=An Error Occurred!
IF EXIST WSCPLog.txt DEL WSCPLog.txt
SET LOG=WSCPLog.txt
START /WAIT WinSCP.exe /console /script=WSCP-GetC.txt /log=%log%
IF ERRORLEVEL 1 GOTO erroryes
IF NOT EXIST "\\server\path\Test_File.ext" GOTO nofilemail
GOTO okmail
:erroryes
%comspec% /c exit %0%
FINDSTR /C:"Test_File.ext: No such file or directory" %LOG%
IF ERRORLEVEL 0 GOTO nofilemail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%FailMailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%FailMailSub% /MESSAGE=%log% /HOST=mail.mydomian.com
GOTO end
:nofilemail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%MailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%NoFileMailSub% /MESSAGE=%log% /HOST=mail.mydomain.com
GOTO end
:okmail
IF EXIST %temp%\rdcto.txt DEL %temp%\rdcto.txt
FOR %%a IN (%MailDst%) DO ECHO %%a>>%temp%\rdcto.txt
"%~dp0sendmail.exe" /TO=%temp%\rdcto.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%OKMailSub% /MESSAGE=%log% /HOST=mail.mydomain.com
:end