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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/133883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 05:23:44  来源:igfitidea点击:

Stop and Start a service via batch or cmd file?

windowscommand-linebatch-filecmd

提问by Keng

How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?

如何编写 bat 或 cmd 脚本以通过错误检查可靠地停止和启动服务(或者让我知道它由于某种原因没有成功)?

回答by Ferruccio

Use the SC(service control) command, it gives you a lot more options than just start& stop.

使用SC(service control) 命令,它为您提供了比start&更多的选项stop

  DESCRIPTION:
          SC is a command line program used for communicating with the
          NT Service Controller and services.
  USAGE:
      sc <server> [command] [service name]  ...

      The option <server> has the form "\ServerName"
      Further help on commands can be obtained by typing: "sc [command]"
      Commands:
        query-----------Queries the status for a service, or
                        enumerates the status for types of services.
        queryex---------Queries the extended status for a service, or
                        enumerates the status for types of services.
        start-----------Starts a service.
        pause-----------Sends a PAUSE control request to a service.
        interrogate-----Sends an INTERROGATE control request to a service.
        continue--------Sends a CONTINUE control request to a service.
        stop------------Sends a STOP request to a service.
        config----------Changes the configuration of a service (persistant).
        description-----Changes the description of a service.
        failure---------Changes the actions taken by a service upon failure.
        qc--------------Queries the configuration information for a service.
        qdescription----Queries the description for a service.
        qfailure--------Queries the actions taken by a service upon failure.
        delete----------Deletes a service (from the registry).
        create----------Creates a service. (adds it to the registry).
        control---------Sends a control to a service.
        sdshow----------Displays a service's security descriptor.
        sdset-----------Sets a service's security descriptor.
        GetDisplayName--Gets the DisplayName for a service.
        GetKeyName------Gets the ServiceKeyName for a service.
        EnumDepend------Enumerates Service Dependencies.

      The following commands don't require a service name:
      sc <server> <command> <option>
        boot------------(ok | bad) Indicates whether the last boot should
                        be saved as the last-known-good boot configuration
        Lock------------Locks the Service Database
        QueryLock-------Queries the LockStatus for the SCManager Database
  EXAMPLE:
          sc start MyService

回答by Bill Michell

net start [serviceName]

and

net stop [serviceName]

tell you whether they have succeeded or failed pretty clearly. For example

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

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

More help is available by typing NET HELPMSG 3521.

If running from a batch file, you have access to the ERRORLEVEL of the return code. 0 indicates success. Anything higher indicates failure.

如果从批处理文件运行,您可以访问返回代码的 ERRORLEVEL。0 表示成功。任何更高的值都表示失败。

As a bat file, error.bat:

作为 bat 文件,error.bat

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

The output looks like this:

输出如下所示:

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 . . .

Return Codes

返回代码

 - 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

Edit 20.04.2015

编辑 20.04.2015

Return Codes:

返回代码:

The NET command does not return the documented Win32_Service class return codes (Service Not Active,Service Request Timeout, etc) and for many errors will simply return Errorlevel 2.

NET 命令不会返回记录在案的 Win32_Service 类返回代码(服务未激活、服务请求超时等),并且对于许多错误,只会返回错误级别 2。

Look here: http://ss64.com/nt/net_service.html

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

回答by Jonas Gulle

You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.

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

Disclaimer: I've written this from the top of my head, but I think it'll work.

免责声明:我是从头开始写的,但我认为它会起作用。

回答by vanval

Instead of checking codes, this works too

这也适用,而不是检查代码

net start "Apache tomcat" || goto ExitError

:End  
exit 0  

:ExitError  
echo An error has occurred while starting the tomcat services  
exit 1  

回答by Nathanial Wilson

I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit. I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.

我为此创建了我的个人批处理文件,我的有点不同,但可以根据需要随意修改。不久前我创建了这个,因为我很无聊,想为人们提供一种简单的方式来输入结束、开始、停止或设置为自动。此 BAT 文件仅要求您输入服务名称,其余的将由它来完成。我没有意识到他正在寻找说明任何错误的东西,我一定是误读了那部分。虽然通常这可以通过在行尾输入 >> output.txt 来完成。

The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.

%var% 只是让用户能够将自己的服务输入到其中的一种方式,而不必每次要启动/停止不同的服务时都去修改 bat 文件。

If I am wrong, anyone can feel free to correct me on this.

如果我错了,任何人都可以随时纠正我。

@echo off
set /p c= Would you like to start a service [Y/N]?
  if /I "%c%" EQU "Y" goto :1
  if /I "%c%" EQU "N" goto :2
    :1  
    set /p var= Service name: 
:2 
set /p c= Would you like to stop a service [Y/N]?
  if /I "%c%" EQU "Y" goto :3
  if /I "%c%" EQU "N" goto :4
    :3  
    set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
  if /I "%c%" EQU "Y" goto :5
  if /I "%c%" EQU "N" goto :6
    :5  
    set /p var2= Service name:
:6 
set /p c= Would you like to set a service to auto [Y/N]?
  if /I "%c%" EQU "Y" goto :7
  if /I "%c%" EQU "N" goto :10
    :7  
    set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto

回答by ZombieSheep

Using the return codes from net startand net stopseems like the best method to me. Try a look at this: Net Start return codes.

从使用返回代码net start,并net stop似乎对我最好的方法。试试看这个:Net Start return codes

回答by ATSiem

Syntax always gets me.... so...

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

Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver

如果您是两台机器上的管理员,以管理员身份运行 .bat,并且这些机器位于同一个域中,那么这里明确地向批处理文件添加一行将终止远程服务(在另一台机器上)。机器名称遵循 UNC 格式 \myserver

sc \ip.ip.ip.ip stop p4_1

In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.

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

For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'

对于您的 Service Ops 迷……请务必附加您的原因代码和评论!即“4”等于“计划”并注释“停止服务器进行维护”

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

回答by DaveH

We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.

我们认为“net stop”会停止服务。可悲的是,现实并不是那么黑白分明。如果服务需要很长时间停止,该命令将在服务停止之前返回。但是,除非您检查错误级别,否则您不会知道。

The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

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

But then again...

但话又说回来...

I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

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

回答by Clinton

I just used Jonas' example above and created full list of 0 to 24 errorlevels. Other post is correct that net startand net stoponly use errorlevel0 for success and 2 for failure.

我只是使用了上面 Jonas 的示例,并创建了 0 到 24 个错误级别的完整列表。其他职位是正确的,net start并且net stop只使用errorlevel失败0成功和2。

But this is what worked for me:

但这对我有用:

net stop postgresql-9.1
if %errorlevel% == 2 echo Access Denied - Could not stop service
if %errorlevel% == 0 echo Service stopped successfully
echo Errorlevel: %errorlevel%

Change stopto startand works in reverse.

更改stopstart并反向工作。

回答by Kuleris

Manual service restart is ok - services.msc has "Restart" button, but in command line both sc and net commands lacks a "restart" switch and if restart is scheduled in cmd/bat file, service is stopped and started immediately, sometimes it gets an error because service is not stopped yet, it needs some time to shut things down.

手动重启服务没问题 - services.msc 有“重启”按钮,但在命令行中 sc 和 net 命令都缺少“重启”开关,如果重启是在 cmd/bat 文件中安排的,服务会立即停止并启动,有时它出现错误,因为服务尚未停止,需要一些时间来关闭。

This may generate an error: sc stop sc start

这可能会产生错误:sc stop sc start

It is a good idea to insert timeout, I use ping (it pings every 1 second): sc stop ping localhost -n 60 sc start

插入超时是个好主意,我使用 ping(它每 1 秒 ping 一次): sc stop ping localhost -n 60 sc start