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


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

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

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

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

使用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

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

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

这也可以代替检查代码

net start "Apache tomcat" || goto ExitError

:End  
exit 0  

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

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

下面显式地介绍了如何向批处理文件中添加一行,如果您是两台机器上的管理员,以管理员身份运行.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

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

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

但话说回来……

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

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.

%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

我只是使用上面Jonas的例子,创建了一个完整的0到24个错误级别的列表。另一篇文章是正确的,网络启动和网络停止只使用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%

将停止改为开始并反向工作。

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

这可能会产生一个错误: sc停止 sc开始

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

有时你会发现停不动。

我的SQlServer有时会这样做。使用下面的命令行杀死它。如果你真的真的需要你的剧本来消灭那些不停的东西。作为最后的手段,我会让它这么做

taskkill /pid [pid number] /f

我正在用c#写一个windows服务,停止/卸载/构建/安装/启动循环太累人了。写了一个小脚本,命名为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%

也许这能帮助到某些人:)

下面是Windows 10使用批量启动系统还原的命令:

sc config swprv start= Auto

你可能也会喜欢这些命令:

更改注册表值为自动启动系统恢复 REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" /v DisableSR /t REG_DWORD /d 0 /f 创建系统还原点 Wmic.exe /Namespace:\root\default Path SystemRestore Call CreateRestorePoint "djibe saved your PC", 100,12 修改“系统恢复”磁盘使用率 vssadmin调整shadowstorage /for=C: /on=C: /maxsize=10%

享受

SC 净停止/启动 PsService WMIC Powershell还有易于使用的选项

SC和NET已经作为答案给出了。PsService增加了一些简洁的功能,但需要从微软下载。

但我最喜欢的方式是WMIC,因为WQL语法提供了一种强大的方式,可以用一行管理多个服务(WMI对象也可以通过powershell/vbscript/jscript/c#使用)。

最简单的使用方法:

wmic service MyService call StartService
wmic service MyService  call StopService

以及WQL的例子

wmic service where "name like '%%32Time%%' and ErrorControl='Normal'" call StartService

这将启动名称包含32Time并具有正常错误控制的所有服务。

这里有一些你可以使用的方法。

:

wmic service get /FORMAT:VALUE

您可以查看有关服务的可用信息。

我没有发现上面的答案提供了一个令人满意的解决方案,所以我写了下面的批处理脚本…

:loop
net stop tomcat8 
sc query tomcat8 | find "STOPPED"
if errorlevel 1 (
  timeout 1
  goto loop
)
:loop2
net start tomcat8
sc query tomcat8 | find "RUNNING"
if errorlevel 1 (
  timeout 1
  goto loop2
)

它一直运行net stop直到服务状态为STOPPED,只有在状态为STOPPED后才运行net start。如果一个服务需要很长时间才能停止,网络停止可能会终止失败。如果由于某种原因,服务没有成功启动,它将继续尝试启动服务,直到状态为RUNNING。

用它可以启动需要服务的服务或程序

@echo
taskkill /im service.exe /f
taskkill /im service.exe /f
set "reply=y"
set /p "reply=Restart service? [y|n]: "
if /i not "%reply%" == "y" goto :eof
cd "C:\Users\user\Desktop"
start service.lnk
sc start service
eof
exit