Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

Batch file: START "" /W CMD /C doesn't seem to work inside a foor loop

I have a batch file and it's content is:

SETLOCAL enabledelayedexpansion
SET /A FT=500
FOR /F "skip=1 tokens=1-6" %%A IN ('START "" /wait WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year
/Format:table ') DO (
 IF NOT !FT!==500 GOTO proceed
 SET  FD=%%F-%%D-%%A
 SET  FT=%%B:%%C:%%E
:proceed
 SET /A FX="DS"
)
echo %FD% %FT% : %* >> "%LOGFILE%"

endlocal

Initially the line

FOR /F "skip=1 tokens=1-6" %%A IN ('START "" /wait WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year
    /Format:table ')

was

FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year
    /Format:table ')

but as running the WMIC command within the batch caused the process to hang therefore I thought of running WMIC command on a new CMD windows and that seems to solve the hang issue, but now the content of the child windows running the WMIC command is not passed to the parent window. (i.e) The output to the log file is just "500" (Value of FT) and not the value of FT that is changed inside in the For loop, due to some reason it just skips the for loop.

Any idea or suggestion why this occurs?

I will really appreciate any suggestion.

Thanks a ton in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@ECHO OFF &SETLOCAL
SET /A FT=500
FOR /F "delims=" %%x IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,SEcond^,Year /Format:table ^|find "20"') DO (
    for /f "tokens=1-6" %%A in ("%%~x") do (
        IF NOT %FT%==500 GOTO proceed
        SET "FD=%%F-%%D-%%A"
        SET "FT=%%B:%%C:%%E"
        :proceed
        SET /A FX="DS"
    )
)
echo %FD% %FT% : %* 

endlocal

You can also use a Tempfile:

@ECHO OFF &SETLOCAL
set "Tempfile=%TEMP%\%random%.~"
WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,SEcond,Year|find "20">"%Tempfile%"
SET /A FT=500
for /f "usebackqtokens=1-6" %%A in ("%Tempfile%") do (
    IF NOT %FT%==500 GOTO proceed
    SET "FD=%%F-%%D-%%A"
    SET "FT=%%B:%%C:%%E"
    :proceed
    SET /A FX="DS"
)
del "%Tempfile%"
echo %FD% %FT% : %* 

Hexdump of the Tempfile:

0000000: 32 39 20 20 20 31 37 20 20 20 20 30 20 20 20 20  29   17    0
0000010: 20 20 20 31 31 20 20 20 20 20 33 39 20 20 20 20     11     39
0000020: 20 20 32 30 31 33 20 20 0d 0d 0a                   2013  ...

Output:

2013-11-29 15:52:59 :

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...