RSS

CMD script that doesn’t work between 1AM – 9AM

07 May

One of the guys in another team complained to me the other day that one of the scheduled tasks which they were running seems to fail between 1 AM and 9 AM daily. The script is a simple CMD batch file and after troubleshooting for a while we could not find any issues with the account used to run the script or any other restrictions, so the focus now goes to the script. So I asked the guy to set echo on and pipe the results to have a look. Part of the script looks like this:

...
for /f "tokens=1,2,3 delims=/" %%i in ("%date%") do set LogDate=%%k-%%j-%%i
for /f "tokens=1,2,3,4 delims=:." %%i in ("%time%") do set LogTime=%%i-%%j-%%k.%%l
SET TMPFOLDER=C:\Mytemp
SET F1=%TMPFOLDER%\%LogDate%_%LogTime%_f1.txt
DIR C:\MYPATH /ad /on /b > %F1%
...

Now this looks exceptionally normal, but when I piped the results, I saw the following output:

C:\scripts>DIR /ad /on /b 9-04-21.20_f1.txt 1>C:\Mytemp\2010-05-07_
The system cannot find the path specified.

That was really strange because if you look at the command for DIR it only pipes to one file, how did we end up with 2 files? A quick look at it, I realized that the file was cut into half, with the second half being “9-04-21.20_f1.txt”.

Okay, so we decided to quote “%F1%” to see what happens and it works! Immediately I could see the problem…

C:\scripts>DIR /ad /on /b 1> "C:\Mytemp\2010-05-07_ 9-04-21.20_f1.txt"

There is a space in the output file! A quick check of the result of the output found the following culprit.

C:\scripts>for /F "tokens=1,2,3,4 delims=:." %i in (" 9:04:21.20") do set LogTime=%i-%j-%k.%l
C:\scripts>set LogTime= 9-04-21.20

The time variable %time% contains a leading space if the hour is between 1 to 9. This explains why the script only works outside 1 AM – 9 AM!

The solution is a quick fix by added [space] as one of the delimiters.

for /f "tokens=1,2,3,4 delims=:. " %%i in ("%time%") do set LogTime=%%i-%%j-%%k.%%l

 

Advertisements
 
Leave a comment

Posted by on May 7, 2010 in Scripts, Windows CMD

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: