Windows Batch - 服务循环,for循环中验证失败

Windows Batch - 服务循环,for循环中验证失败

我正在尝试设置一些验证/计时器,以便在服务需要更长时间才能循环时等待。如果失败,我将使用其他方法解析日志文件,并在失败时通过电子邮件向我发送警报。

由于某种原因,我在 for 循环中遇到了语法错误。如果我删除 else 语句,它就可以正常工作。但我找不到 else 语句中的语法错误。

@echo off
set ServiceName="My Service Name"
set logPath="C:\Program Files\Application"

::Start Service Maintenance
set now=[%DATE:~10,14%-%DATE:~4,2%-%DATE:~7,2%T%TIME:~0,8%]

for /F "tokens=3 delims=: " %%H in ('sc query %ServiceName% ^| findstr "        STATE"') do (
@echo %now% - For Loop >> %logPath%\ServiceManagmentLog.txt
  if /I "%%H" NEQ "STOPPED" (
  @echo %now% - Service Stopped - %ServiceName% >> %logPath%\ServiceManagmentLog.txt ) else (
    @echo %now% - The service doens't seem to be stopping, waiting another 5 seconds and trying again >> %logPath%\ServiceManagmentLog.txt
    ping -n 6 127.0.0.1 > nul
    sc start %ServiceName%
    ping -n 6 127.0.0.1 > nul
    for /F "tokens=3 delims=: " %%I in ('sc query %ServiceName% ^| findstr "        STATE"') do (
      if /I "%%I" NEQ "STOPPED"( 
      @echo %now% - Service Stopped - %ServiceName% >> %logPath%\ServiceManagmentLog.txt    ) else (
      set stopError="%ServiceName% Failed to Stop"
      @echo %now% - ALERT - There seems to be an issue stopping %ServiceName% ) 
      ) 
    ) 
  )

答案1

答案是格式错误。我漏掉了后面的)

for /F "tokens=3 delims=: " %%H in ('sc query %serviceName% ^| findstr "        STATE"') do (
@echo %now% - For Loop >> %logPath%\ServiceManagmentLog_IC_%arg1%.txt
    if /I "%%H" EQU "STOPPED" (
        @echo %now% - Service Stopped - %serviceName% >> %logPath%\ServiceManagmentLog_IC_%arg1%.txt 
    ) else (
        @echo %now% - The service doens't seem to be stopping, waiting another %arg2% seconds and trying again >> %logPath%\ServiceManagmentLog_IC_%arg1%.txt
        ping -n %arg2% 127.0.0.1 > nul
        sc stop %serviceName%
        ping -n %arg2% 127.0.0.1 > nul
        for /F "tokens=3 delims=: " %%H in ('sc query %serviceName% ^| findstr "        STATE"') do (
            if /I "%%H" EQU "STOPPED" ( 
                    @echo %now% - Service Stopped - %serviceName% >> %logPath%\ServiceManagmentLog_IC_%arg1%.txt
                ) else (
                    @echo %now% - ALERT - There seems to be an issue stopping %serviceName% >> %logPath%\ServiceManagmentLog_IC_%arg1%.txt
                ) 
        ) 
    )
)

相关内容