misricko
misricko

Reputation: 13

using an if statement in windows batch file script

I'm completely unfamiliar with windows scripting - I can roughly read it and see what's going on but when it comes to writing I'm basically at zero. Here's what I'm trying to do. I have the following script

echo on

SET LOGNAME=%7
SET LOGNAME=%LOGNAME%.log

Set CURRDATE=%TEMP%\CURRDATE.TMP
Set CURRTIME=%TEMP%\CURRTIME.TMP

DATE /T > %CURRDATE%
TIME /T > %CURRTIME%

Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%l%%k%%j%%i

Set PARSEARG="eol=; tokens=1,2,3,4* delims=:,. "
For /F %PARSEARG% %%i in (%CURRTIME%) Do Set HHMMSS=%%i%%j%%k%%l


sqlcmd -E -S %1 -d %2 -h-1 -b -w 1000 -Q "EXEC spTest %3,%4,%5 " -o %6Test_%YYYYMMDD%%HHMMSS%.DAT

IF ERRORLEVEL 1 GOTO FAILED

ECHO %YYYYMMDD% %HHMMSS% OK>>%LOGNAME%

GOTO END

:FAILED
ECHO %YYYYMMDD% %HHMMSS% FAILED>>%LOGNAME%

:END
EXIT /B %ERRORLEVEL%

Unfortunately from time to time the YYYYMMDD part of the file is missing (no idea why this happens - its very rare - I can only think it might be the odd network glitch). What I want to do is have an if statement so that if YYYYMMDD is empty I set it to some default date. I was inserting the following line to my code - but this doesn't do anything for me.

if %YYYYMMDD% ==" " (set %YYYYMMDD% =20990101)

Any advice please?

Upvotes: 1

Views: 6709

Answers (1)

dbenham
dbenham

Reputation: 130919

Your IF statement is failing for two reasons - the comparison is wrong, and your syntax for the SET is wrong. I believe you want:

if "%YYYYMMDD%"=="" (set YYYYMMDD=20990101)

But I don't understand why you need the above at all. I don't know why you are getting intermitent failure, but it should be fixable.

I do know your existing code can be greatly simplified. There is no need to use temporary files to capture the DATE and TIME values. Dynamic variables %DATE% and %TIME% provide the values you need. Type HELP SET for a list of available dynamic variables. And FOR /F can parse a string using IN("string") syntax. Type HELP FOR for a complete description of the command.

Your code could be changed to look something like this:

for /F %PARSEARG% %%i in ("%DATE%") do set YYYYMMDD=%%l%%k%%j%%i

and

for /F %PARSEARG% %%i in ("%TIME%") do set HHMMSS=%%i%%j%%k%%l

Your existing PARSEARG definitions don't look correct to me, and I think the assignment may have to change as well. Since I don't know your locale settings or your desired output format, I can't tell you exactly how to change it.

If you can't figure it out, post the format you get with %DATE% and %TIME%, as well as the format you want, and I (or someone else) can help further.

Upvotes: 2

Related Questions