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

时间:2021-01-30 06:28:40

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来停止并使用错误检查启动一个可靠的服务(或者让我知道无论出于什么原因它都不成功)?

13 个解决方案

#1


315  

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

使用SC(服务控制)命令,它给您提供了更多的选项,而不仅仅是启动和停止。

  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

#2


180  

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类返回代码(服务不活动、服务请求超时等),对于许多错误,只返回Errorlevel 2。

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

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

#3


26  

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.

免责声明:我已经从我的顶部写了这个,但是我认为它会起作用。

#4


8  

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  

#5


6  

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

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

#6


5  

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'

对于你的服务项目,瘾君子…一定要附加你的原因代码和评论!即。“4”等于“计划”和“停止服务器维护”

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

#7


5  

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文件只是请求您输入服务名称,它将为您完成其余的工作。我没有意识到他在寻找任何错误的东西,我一定是误读了那部分。虽然通常这可以通过输入>>输出来完成。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

#8


4  

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.

我们认为“网络停止”将停止服务。可悲的是,现实并不是黑白分明的。如果服务需要很长时间才能停止,命令将在服务停止之前返回。但是,除非您检查errorlevel,否则您不会知道。

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.

我看到第一个服务要花很长时间才能停止,然后对后续服务的“net stop”似乎什么都不做。查看服务管理器中的服务,它的状态仍然是“开始”——没有更改为“停止”。但是我可以用SCM手动停止第二个服务,它在3或4秒内停止。

#9


3  

or you can start remote service with this cmd : sc \\<computer> start <service>

或者您可以使用这个cmd: sc \\ \ <计算机> 开始 <服务> 。

#10


2  

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

我刚刚使用了Jonas的例子,并创建了0到24个errorlevel的完整列表。其他帖子是正确的,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 stop to start and works in reverse.

改变停止,开始和工作相反。

#11


2  

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.

手动服务重启是ok -服务。msc有“重启”按钮,但在命令行中,sc和net命令都缺少一个“重启”开关,如果在cmd/bat文件中重新启动,服务将立即停止并立即启动,有时会出现错误,因为服务还没有停止,需要一些时间来关闭一些东西。

This may generate an error: sc stop sc start

这可能会产生一个错误:sc停止sc启动。

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秒一次):sc阻止ping localhost -n 60 sc启动。

#12


1  

SC can do everything with services... start, stop, check, configure, and more...

SC可以用服务做任何事情…开始,停止,检查,配置,等等…

#13


1  

Sometimes you can find the stop does not work..

有时你会发现,停止工作是行不通的。

My SQlServer sometimes does this. Using the following commandline kills it. If you really really need your script to kill stuff that doesn't stop. I would have it do this as a last resort

我的SQlServer有时会这样做。使用以下命令行杀死它。如果你真的真的需要你的脚本去杀死那些不停止的东西。我会把它作为最后的手段。

taskkill /pid [pid number] /f

#1


315  

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

使用SC(服务控制)命令,它给您提供了更多的选项,而不仅仅是启动和停止。

  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

#2


180  

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类返回代码(服务不活动、服务请求超时等),对于许多错误,只返回Errorlevel 2。

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

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

#3


26  

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.

免责声明:我已经从我的顶部写了这个,但是我认为它会起作用。

#4


8  

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  

#5


6  

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

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

#6


5  

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'

对于你的服务项目,瘾君子…一定要附加你的原因代码和评论!即。“4”等于“计划”和“停止服务器维护”

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

#7


5  

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文件只是请求您输入服务名称,它将为您完成其余的工作。我没有意识到他在寻找任何错误的东西,我一定是误读了那部分。虽然通常这可以通过输入>>输出来完成。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

#8


4  

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.

我们认为“网络停止”将停止服务。可悲的是,现实并不是黑白分明的。如果服务需要很长时间才能停止,命令将在服务停止之前返回。但是,除非您检查errorlevel,否则您不会知道。

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.

我看到第一个服务要花很长时间才能停止,然后对后续服务的“net stop”似乎什么都不做。查看服务管理器中的服务,它的状态仍然是“开始”——没有更改为“停止”。但是我可以用SCM手动停止第二个服务,它在3或4秒内停止。

#9


3  

or you can start remote service with this cmd : sc \\<computer> start <service>

或者您可以使用这个cmd: sc \\ \ <计算机> 开始 <服务> 。

#10


2  

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

我刚刚使用了Jonas的例子,并创建了0到24个errorlevel的完整列表。其他帖子是正确的,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 stop to start and works in reverse.

改变停止,开始和工作相反。

#11


2  

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.

手动服务重启是ok -服务。msc有“重启”按钮,但在命令行中,sc和net命令都缺少一个“重启”开关,如果在cmd/bat文件中重新启动,服务将立即停止并立即启动,有时会出现错误,因为服务还没有停止,需要一些时间来关闭一些东西。

This may generate an error: sc stop sc start

这可能会产生一个错误:sc停止sc启动。

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秒一次):sc阻止ping localhost -n 60 sc启动。

#12


1  

SC can do everything with services... start, stop, check, configure, and more...

SC可以用服务做任何事情…开始,停止,检查,配置,等等…

#13


1  

Sometimes you can find the stop does not work..

有时你会发现,停止工作是行不通的。

My SQlServer sometimes does this. Using the following commandline kills it. If you really really need your script to kill stuff that doesn't stop. I would have it do this as a last resort

我的SQlServer有时会这样做。使用以下命令行杀死它。如果你真的真的需要你的脚本去杀死那些不停止的东西。我会把它作为最后的手段。

taskkill /pid [pid number] /f