服务启动和停止的批处理文件

时间:2016-04-20 07:31:39

标签: batch-file

我正在处理一个批处理文件,其中我想停止一个服务然后另一个服务,之后将同时重新启动服务。 以下是示例代码:

for /F "tokens=*" %%A in (servers_stop_All.txt) do (

echo %%A >> "log\MyService_stop_log_%datetime%.txt"
 sc \\%%A stop MyService >> "log\MYService_stop_log_%datetime%.txt")


:CHECK1

for /F "tokens=3 delims=: " %%H in ('sc query "MyService" ^| findstr " STATE"') do (
  if /I "%%H" EQU "STOPPED" (

   GOTO :STOP_JBOSS
  ) ELSE (
GOTO :CHECK1
)
)


:STOP_JBOSS
for /F "tokens=*" %%A in (servers_stop_All.txt) do (
echo %%A >> "log\jboss_stop_log_%datetime%.txt"

sc \\%%A stop jboss_qa >> "log\jboss_stop_log_%datetime%.txt"
)

第一项服务已停止,但无法检查条件并进入下一项活动。

1 个答案:

答案 0 :(得分:0)

下一个代码段可以提供帮助(关键点已注释,请参阅代码中的所有rem):

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

rem obtain %datetime% variable in locale independent yyyymmddHHMMSS format
for /f "tokens=2 delims==" %%G in (
  'wmic OS get localdatetime /value') do set "datetime=%%G"
set "datetime=%datetime:~0,14%"

rem loop: read server list and stop services
for /F "tokens=*" %%A in (servers_stop_All.txt) do (
  set "server=%%A"
  call :stopAService MyService
  If errorlevel 1 (
        rem %server%: MyService unknown at all
    ) else (
        rem %server%: MyService stopped succesfully
        call :stopAService jboss_qa
    )
  rem finish manipulation for particular server here 
)
GOTO :continue

:stopAService
  rem subroutine to stop a service and wait until it's state is not STOPPED 
  rem input parameter: service name
  echo %server% >> "log\%~1_stop_log_%datetime%.txt"
  sc \\%server% stop %~1 >> "log\%~1_stop_log_%datetime%.txt")
  rem       SC command would raise errorlevel >0 in case of no success
  rem 1062: The service has not been started.
  If %errorlevel% EQU 1062 exit /B 0
  rem 1060: The specified service does not exist as an installed service.
  If %errorlevel% EQU 1060 exit /B 1060 
:CHECK1
  rem add some time to wait for state change from "STOP_PENDING" to "STOPPED"?
  >NUL TIMEOUT /T 5 /NOBREAK
  for /F "tokens=3 delims=: " %%H in ('sc query "%~1" ^| findstr "STATE"') do (
    if /I "%%H" EQU "STOPPED" (
        rem Success
    ) ELSE (
        GOTO :CHECK1
    )
  )
rem return from subroutine with exit code 0
exit /B 0

:continue
rem finish script here