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


当前回答

语法总是让我....所以…

下面显式地介绍了如何向批处理文件中添加一行,如果您是两台机器上的管理员,以管理员身份运行.bat,并且两台机器位于同一个域中,则该批处理文件将终止远程服务(在另一台机器上)。机器名称遵循UNC格式\myserver

sc \\ip.ip.ip.ip stop p4_1

在这种情况下……当您在服务管理器中查看服务的属性时,p4_1是服务名称和显示名称。您必须使用服务名称。

对于你们的服务运营迷…一定要附上你的理由代码和评论!即。“4”等于“计划”和注释“停止服务器维护”

sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance

其他回答

SC可以用服务做任何事情……启动,停止,检查,配置,和更多…

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

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

我们愿意认为“网络停止”将停止服务。遗憾的是,现实并不是那么非黑即白。如果停止服务的时间较长,则该命令将在服务停止之前返回。但是,除非检查errorlevel,否则您不会知道。

解决方案似乎是循环查找服务的状态,直到停止,并在每次循环中暂停。

但话说回来……

我看到第一个服务需要很长时间才能停止,然后后续服务的“净停止”似乎什么也不做。在服务管理器中查看服务,它的状态仍然是“Started”—没有更改为“stopped”。然而,我可以使用SCM手动停止第二个服务,它将在3或4秒内停止。

语法总是让我....所以…

下面显式地介绍了如何向批处理文件中添加一行,如果您是两台机器上的管理员,以管理员身份运行.bat,并且两台机器位于同一个域中,则该批处理文件将终止远程服务(在另一台机器上)。机器名称遵循UNC格式\myserver

sc \\ip.ip.ip.ip stop p4_1

在这种情况下……当您在服务管理器中查看服务的属性时,p4_1是服务名称和显示名称。您必须使用服务名称。

对于你们的服务运营迷…一定要附上你的理由代码和评论!即。“4”等于“计划”和注释“停止服务器维护”

sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance
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