通过批处理或cmd文件停止和启动一个服务?

我如何编写一个bat或cmd脚本来可靠地停止和启动一个服务,并进行错误检查(或让我知道由于某种原因没有成功)?

net start [serviceName]

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类的返回代码(Service Not Active,Service Request Timeout,等等),对于许多错误,将简单地返回Errorlevel 2。

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

评论(5)

你可以使用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%

免责声明:这是我凭空写的,但我认为它能行。

评论(1)

对我来说,使用net start'和net stop'的返回代码似乎是最好的方法。试着看一下这个。网络启动返回代码

评论(1)