代码之家  ›  专栏  ›  技术社区  ›  Keng

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

  •  264
  • Keng  · 技术社区  · 16 年前

    我如何编写BAT或CMD脚本,以便通过错误检查可靠地停止和启动服务(或者让我知道,无论出于什么原因,它都没有成功)?

    15 回复  |  直到 6 年前
        1
  •  325
  •   Ferruccio    10 年前

    使用 SC (服务控制)命令,它为您提供了许多选项,而不仅仅是 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
    
        2
  •  193
  •   Martin R. Bill Michell    10 年前
    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.
    

    如果从批处理文件运行,则可以访问返回代码的错误级别。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_服务类返回代码(服务未激活、服务请求超时等),对于许多错误,只返回错误级别2。

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

        3
  •  27
  •   Jonas Engström    16 年前

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

    免责声明:我已经从头开始写了这篇文章,但我认为它会起作用。

        4
  •  8
  •   Mr_Green    9 年前

    不检查代码,这也有效

    net start "Apache tomcat" || goto ExitError
    
    :End  
    exit 0  
    
    :ExitError  
    echo An error has occurred while starting the tomcat services  
    exit 1  
    
        5
  •  7
  •   Nathanial Wilson    6 年前

    我已经为这个创建了我的个人批处理文件,我的有点不同,但是您可以随意修改。 我在不久前就创建了这个,因为我很无聊,想为人们提供一个简单的方法,让他们能够输入结束、开始、停止或设置为自动。这个BAT文件只是请求您输入服务名,它将为您完成其余的工作。我不知道他在找什么错误的东西,我一定是看错了。尽管通常可以通过在行的末尾输入>>output.txt来完成。

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

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

    @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
    
        6
  •  6
  •   bluish dmajkic    13 年前

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

        7
  •  5
  •   ATSiem    11 年前

    语法总是让我…所以…

    这里明确地介绍了如何在批处理文件中添加一行,该行将杀死远程服务(在另一台计算机上)。如果您是两台计算机上的管理员,请以管理员身份运行.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
    
        8
  •  4
  •   DaveH    11 年前

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

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

    但是再一次…

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

        9
  •  3
  •   onionpsy    13 年前

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

        10
  •  2
  •   Clinton    9 年前

    我刚才使用了jonas的例子,创建了0到24个错误级别的完整列表。其他职位是正确的 net start net stop 只使用 errorlevel 0代表成功,2代表失败。

    但这对我很有用:

    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%
    

    变化 stop start 然后反向工作。

        11
  •  2
  •   Kuleris    9 年前

    手动服务重新启动正常-services.msc有“restart”按钮,但在命令行中sc和net命令都缺少“restart”开关,如果在cmd/bat文件中计划重新启动,则服务会立即停止并启动,有时会因为服务尚未停止而出错,需要一些时间来关闭。

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

    插入超时是一个好主意,我使用ping(它每1秒ping一次): SC停止 Ping本地主机-N 60 SC启动

        12
  •  1
  •   bluish dmajkic    13 年前

    SC 可以用服务做一切…启动、停止、检查、配置等…

        13
  •  1
  •   andrew pate    7 年前

    有时你会发现停站不起作用。

    我的SQLServer有时会这样做。使用下面的命令行可以杀死它。如果你真的需要你的脚本来杀死那些无法停止的东西。我会让它做最后的选择

    taskkill /pid [pid number] /f
    
        14
  •  1
  •   djibe    6 年前

    以下是使用批处理启动系统还原的Windows 10命令:

    sc config swprv start= Auto
    

    您也可能喜欢这些命令:

    • 将注册表值更改为自动启动系统还原

      注册表添加“hklm\software\microsoft\windows nt\currentversion\systemrestore”/v disablesr/t注册表双字/d 0/f

    • 创建系统还原点

      wmic.exe/namespace:\root\default path systemrestore call createstorepoint“djibe saved your pc”,100,12

    • 更改系统还原磁盘使用率

      vssadmin调整阴影存储大小/for=c:/on=c:/maxsize=10%

    享受

        15
  •  0
  •   sh87    6 年前

    我正在用C语言编写一个Windows服务,stop/uninstall/build/install/start循环太累了。写了一个小剧本,叫它 reploy.bat 并将其放到我的Visual Studio输出目录(其中一个目录具有内置的服务可执行文件)中,以自动执行循环。

    只需设置这3个变量

    servicename :这显示在Windows服务控制面板(services.msc)上。

    slndir :包含解决方案(.sln)文件的文件夹(不是完整路径)

    binpath :从生成到服务可执行文件的完整路径(不是文件夹路径)

    注意:这需要从Visual Studio开发人员命令行运行 msbuild 命令工作。

    SET servicename="My Amazing Service"
    SET slndir="C:dir\that\contains\sln\file"
    SET binpath="C:path\to\service.exe"
    SET currdir=%cd%
    
    call net stop %servicename%
    call sc delete %servicename%
    cd %slndir%
    call msbuild 
    cd %bindir%
    call sc create %servicename% binpath=%binpath%
    call net start %servicename%
    cd %currdir%
    

    也许这对某人有帮助:)