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


当前回答

这也可以代替检查代码

net start "Apache tomcat" || goto ExitError

:End  
exit 0  

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

其他回答

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

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

@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

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

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

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

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

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