服务启动和停止的批处理文件 [英] Batch file for Services Start and stop
本文介绍了服务启动和停止的批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理一个批处理文件,在该文件中我想停止一项服务,然后停止另一项服务,此后将同时重新启动服务. 下面是示例代码:
I am working on a batch file in which I wanted to stop one service and then another and after that will restart the services simultaneously. Below is the sample code:
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"
)
第一个服务已停止,但无法检查条件并转到下一个活动.
The first service is getting stopped but it is unable to check for the condition and going to next activity.
推荐答案
下一个代码段可能会有所帮助(注释了关键点,请参见代码中的所有rem
):
Next code snippet could help (crucial points are commented, see all rem
in code):
@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
这篇关于服务启动和停止的批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文