我怎么能脚本一个蝙蝠或cmd停止和启动一个服务可靠的错误检查(或让我知道它不成功的原因)?


当前回答

用它可以启动需要服务的服务或程序

@echo
taskkill /im service.exe /f
taskkill /im service.exe /f
set "reply=y"
set /p "reply=Restart service? [y|n]: "
if /i not "%reply%" == "y" goto :eof
cd "C:\Users\user\Desktop"
start service.lnk
sc start service
eof
exit

其他回答

对我来说,使用net start和net stop的返回代码似乎是最好的方法。试着看看这个:Net Start返回代码。

net start [serviceName]

and

net stop [serviceName]

清楚地告诉你他们是成功了还是失败了。例如

U:\>net stop alerter
The Alerter service is not started.

More help is available by typing NET HELPMSG 3521.

如果从批处理文件运行,则可以访问返回代码的ERRORLEVEL。0表示成功。高于这个数值意味着失败。

作为bat文件,error.bat:

@echo off
net stop alerter
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause

输出如下所示:

U:\>error.bat
The Alerter service is not started.

More help is available by typing NET HELPMSG 3521.

There was a problem
Press any key to continue . . .

返回代码

 - 0 = Success
 - 1 = Not Supported
 - 2 = Access Denied
 - 3 = Dependent Services Running
 - 4 = Invalid Service Control
 - 5 = Service Cannot Accept Control
 - 6 = Service Not Active
 - 7 = Service Request Timeout
 - 8 = Unknown Failure
 - 9 = Path Not Found
 - 10 = Service Already Running
 - 11 = Service Database Locked
 - 12 = Service Dependency Deleted
 - 13 = Service Dependency Failure
 - 14 = Service Disabled
 - 15 = Service Logon Failure
 - 16 = Service Marked For Deletion
 - 17 = Service No Thread
 - 18 = Status Circular Dependency
 - 19 = Status Duplicate Name
 - 20 = Status Invalid Name
 - 21 = Status Invalid Parameter 
 - 22 = Status Invalid Service Account
 - 23 = Status Service Exists
 - 24 = Service Already Paused

编辑20.04.2015

返回代码:

NET命令不会返回文档中的Win32_Service类返回码(服务未激活,服务请求超时等),对于许多错误将简单地返回Errorlevel 2。

看这里:http://ss64.com/nt/net_service.html

我没有发现上面的答案提供了一个令人满意的解决方案,所以我写了下面的批处理脚本…

:loop
net stop tomcat8 
sc query tomcat8 | find "STOPPED"
if errorlevel 1 (
  timeout 1
  goto loop
)
:loop2
net start tomcat8
sc query tomcat8 | find "RUNNING"
if errorlevel 1 (
  timeout 1
  goto loop2
)

它一直运行net stop直到服务状态为STOPPED,只有在状态为STOPPED后才运行net start。如果一个服务需要很长时间才能停止,网络停止可能会终止失败。如果由于某种原因,服务没有成功启动,它将继续尝试启动服务,直到状态为RUNNING。

您可以使用NET START命令,然后检查ERRORLEVEL环境变量,例如。

net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%

免责声明:这是我从脑子里写出来的,但我认为它会起作用。

或者您可以使用以下CMD启动远程服务:sc \\<computer> start <service>