Batch File auto quits. I can't find the error

风格不统一 提交于 2020-01-13 20:44:28

问题


I have been coding a small thing that, rather stupidly, has been taking me a while. What it is meant to do is always have a certain excel spreadsheet (named Homework.xlsx) open between two certain times (4:30 and 5:30). The thing is it doesn't actually stay open to check for those times, even though I have it set to a loop that repeats every minute. Here is the code:

SET "stime=16:30:00.00"
SET "etime=17:30:00.00"
:start
TASKLIST /FI "IMAGENAME EQ EXCEL.EXE" 2>NUL | FIND /I /N "EXCEL.EXE" >NUL
IF %ERRORLEVEL% = 0 (
    SET Erunning=true
) ELSE (
    SET Erunning=false
)
IF EXIST C:\Users\Hunter\Documents\HOMEWORKSHEETISOPEN.txt (
    IF %Erunning%=false (
        DEL C:\Users\Hunter\Documents\HOMEWORKSHEETISOPEN.txt
    )
)
IF EXIST C:\Users\Hunter\Documents\HOMEWORKSHEETISOPEN.txt (
    SET running=true
) ELSE (
    SET running=false
)
FOR /F %%F IN ('wmic path win32_localtime get dayofweek^|Findstr [0-6]') DO SET DOW=%%F
IF %time% GEQ %stime% IF %time% LEQ %etime% IF %running%==false IF %DOW% NEQ 6 IF %DOW% NEQ 0 (
   START /MAX C:\Users\Hunter\OneDrive\Homework.xlsx
   ECHO IMRUNNING > C:\Users\Hunter\Documents\HOMEWORKSHEETISOPEN.txt 
)
TIMEOUT 60 /NOBREAK > NUL
GOTO start

回答1:


Your code is not just convoluted, but also inefficient. If the purpose is open an excel spreadsheet in Monday..Friday @ %stime%...%etime% range, then there are simpler ways to do that. For example:

SET "stime=16:30:00.00"
SET "etime=17:30:00.00"

:start

rem Check the day
FOR /F %%F IN ('wmic path win32_localtime get dayofweek^|Findstr [0-6]') DO SET DOW=%%F
IF %DOW% EQU 0 GOTO wait1hour
IF %DOW% EQU 6 GOTO wait1hour

rem Check the time
IF %time% LSS %stime% GOTO wait1min
IF %time% GTR %etime% GOTO wait1min

rem Open the spreadsheet and wait until it is closed
START /MAX C:\Users\Hunter\OneDrive\Homework.xlsx  |  PAUSE > NUL
GOTO start

:wait1min
TIMEOUT 60 /NOBREAK > NUL
GOTO start

:wait1hour
TIMEOUT 3600 /NOBREAK > NUL
GOTO start

You may also calculate the exact number of seconds to wait if the %time% check fail, so the wait method be more efficient; I suggest you to use this method for such a calculation. You may also start the program in Mon..Fri range at the desired hour using the Windows Task Scheduler.



来源:https://stackoverflow.com/questions/42869222/batch-file-auto-quits-i-cant-find-the-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!