windows 如何通过批处理文件检查服务是否正在运行并启动它,如果它没有运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3325081/
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 07:29:48  来源:igfitidea点击:

How to check if a service is running via batch file and start it, if it is not running?

windowswindows-servicesbatch-filescheduled-tasks

提问by citronas

I want to write a batch file that performs the following operations:

我想编写一个执行以下操作的批处理文件:

  • Check if a service is running
    • If is it running, quit the batch
    • If it is not running, start the service
  • 检查服务是否正在运行
    • 如果正在运行,请退出批处理
    • 如果它没有运行,请启动该服务

The code samples I googled so far turned out not to be working, so I decided not to post them.

到目前为止,我在 google 上搜索的代码示例都不起作用,所以我决定不发布它们。

Starting a service is done by:

通过以下方式启动服务:

net start "SERVICENAME"
  1. How can I check if a service is running, and how to make an if statement in a batchfile?
  2. I'm a bit confused. What is the argument I have to pass onto the net start? The service name or its display name?
  1. 如何检查服务是否正在运行,以及如何在批处理文件中创建 if 语句?
  2. 我有点困惑。我必须传递到网络开始的论点是什么?服务名称或其显示名称?

回答by lc.

To check a service's state, use sc query <SERVICE_NAME>. For if blocks in batch files, check the documentation.

要检查服务的状态,请使用sc query <SERVICE_NAME>. 对于批处理文件中的 if 块,请查看文档

The following code will check the status of the service MyServiceNameand start it if it is not running (the if block will be executed if the service is not running):

下面的代码将检查服务的状态,MyServiceName如果它没有运行就启动它(如果服务没有运行,将执行 if 块):

for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr "        STATE"') do (
  if /I "%%H" NEQ "RUNNING" (
   REM Put your code you want to execute here
   REM For example, the following line
   net start "MyServiceName"
  )
)

Explanation of what it does:

解释它的作用:

  1. Queries the properties of the service.
  2. Looks for the line containing the text "STATE"
  3. Tokenizes that line, and pulls out the 3rd token, which is the one containing the state of the service.
  4. Tests the resulting state against the string "RUNNING"
  1. 查询服务的属性。
  2. 查找包含文本“STATE”的行
  3. 标记该行,并取出第三个标记,即包含服务状态的标记。
  4. 根据字符串“RUNNING”测试结果状态

As for your second question, the argument you will want to pass to net startis the service name, notthe display name.

至于您的第二个问题,您要传递给的参数net start是服务名称,而不是显示名称。

回答by Coops

To toggle a service use the following;

要切换服务,请使用以下命令;

NET START "Distributed Transaction Coordinator" ||NET STOP "Distributed Transaction Coordinator"

NET START“分布式事务协调器” ||NET STOP“分布式事务协调器”

回答by LittleBobbyTables - Au Revtheitroad

You can use the following command to see if a service is running or not:

您可以使用以下命令查看服务是否正在运行:

sc query [ServiceName] | findstr /i "STATE"

When I run it for my NOD32 Antivirus, I get:

当我为 NOD32 Antivirus 运行它时,我得到:

STATE                       : 4 RUNNING

If it was stopped, I would get:

如果它被停止,我会得到:

STATE                       : 1 STOPPED

You can use this in a variable to then determine whether you use NET START or not.

您可以在变量中使用它来确定是否使用 NET START。

The service name should be the service name, not the display name.

服务名称应该是服务名称,而不是显示名称。

回答by Kristina Brooks

That should do it:

那应该这样做:

FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)

回答by Dr.eel

Language independent version.

语言独立版本。

@Echo Off
Set ServiceName=Jenkins


SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
    echo %ServiceName% not running 
    echo Start %ServiceName%

    Net start "%ServiceName%">nul||(
        Echo "%ServiceName%" wont start 
        exit /b 1
    )
    echo "%ServiceName%" started
    exit /b 0
)||(
    echo "%ServiceName%" working
    exit /b 0
)

回答by sagelightning

I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.

我刚刚找到这个线程,如果这个人不想使用批处理文件来重新启动服务,我想添加到讨论中。在 Windows 中,如果您转到“服务”、“服务属性”和“恢复”,则有一个选项。您可以在此处设置服务的参数。如果服务停止,喜欢重新启动服务。此外,您甚至可以让第二次失败尝试做一些与重新启动计算机不同的事情。

回答by Daniel Serrano

Cuando se use Windows en Espa?ol, el código debe quedar asi (when using Windows in Spanish, code is):

Cuando se use Windows en Espa?ol, el código debe quedar asi(在西班牙语中使用 Windows 时,代码为):

for /F "tokens=3 delims=: " %%H in ('sc query MYSERVICE ^| findstr "        ESTADO"') do (
  if /I "%%H" NEQ "RUNNING" (
    REM Put your code you want to execute here
    REM For example, the following line
    net start MYSERVICE
  )
)

Reemplazar MYSERVICE con el nombre del servicio que se desea procesar. Puedes ver el nombre del servicio viendo las propiedades del servicio. (Replace MYSERVICE with the name of the service to be processed. You can see the name of the service on service properties.)

Reemplazar MYSERVICE con el nombre del servicio que se desea procesar。Puedes ver el nombre del servicio viendo las propiedades del servicio。(将 MYSERVICE 替换为要处理的服务的名称。您可以在服务属性上看到该服务的名称。)

回答by Logan78

@echo off

color 1F


@sc query >%COMPUTERNAME%_START.TXT


find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul

IF ERRORLEVEL 0 EXIT

IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"

回答by Magige Daniel

For Windows server 2012 below is what worked for me. Replace only "SERVICENAME" with actual service name:

对于下面的 Windows Server 2012,对我有用。仅用实际服务名称替换“SERVICENAME”:

@ECHO OFF
SET SvcName=SERVICENAME

SC QUERYEX "%SvcName%" | FIND "STATE" | FIND /v "RUNNING" > NUL && (
    ECHO %SvcName% is not running 
    ECHO START %SvcName%

    NET START "%SvcName%" > NUL || (
        ECHO "%SvcName%" wont start 
        EXIT /B 1
    )
    ECHO "%SvcName%" is started
    EXIT /B 0
) || (
    ECHO "%SvcName%" is running
    EXIT /B 0
)

回答by KR Akhil

Starting Service using Powershell script. You can link this to task scheduler and trigger it at intervals or as needed. Create this as a PS1 file i.e. file with extension PS1 and then let this file be triggered from task scheduler.

使用 Powershell 脚本启动服务。您可以将其链接到任务计划程序并每隔一段时间或根据需要触发它。将此文件创建为 PS1 文件,即扩展名为 PS1 的文件,然后让此文件从任务调度程序中触发。

To start stop service

启动停止服务

in task scheduler if you are using it on server use this in arguments

在任务调度程序中,如果您在服务器上使用它,请在参数中使用它

-noprofile -executionpolicy bypass -file "C:\Service Restart Scripts\StopService.PS1"

-noprofile -executionpolicy bypass -file "C:\Service Restart Scripts\StopService.PS1"

verify by running the same on cmd if it works it should work on task scheduler also

通过在 cmd 上运行相同的命令来验证它是否工作它也应该在任务调度程序上工作

$Password = "Enter_Your_Password"
$UserAccount = "Enter_Your_AccountInfor"
$MachineName = "Enter_Your_Machine_Name"
$ServiceList = @("test.SocketService","test.WcfServices","testDesktopService","testService")
$PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserAccount, $PasswordSecure 

$LogStartTime = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
$FileDateTimeStamp = Get-Date -Format "MM-dd-yyyy_hh"
$LogFileName = "C:\Users\krakhil\Desktop\Powershell\Logs\StartService_$FileDateTimeStamp.txt" 


#code to start the service

"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"######################  STARTING SERVICE  ##########################" >> $LogFileName

for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName

Write-Output "`n####################################"
Write-Output "Starting Service - " $ServiceList[$i]

"$LogStartTime => Starting Service: $ServiceName" >> $LogFileName
Start-Service $ServiceList[$i]

$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}

if($ServiceState.Status -eq "Running")
{
"$LogStartTime => Started Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Started Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`n Service didn't Start. Current State is - "
Write-Host $ServiceState.Status
}
}

#code to stop the service

"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"######################  STOPPING SERVICE  ##########################" >> $LogFileName

for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName

Write-Output "`n####################################"
Write-Output "Stopping Service - " $ServiceList[$i]

"$LogStartTime => Stopping Service: $ServiceName" >> $LogFileName
Stop-Service $ServiceList[$i]

$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}

if($ServiceState.Status -eq "Stopped")
{
"$LogStartTime => Stopped Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Stopped Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`nService didn't Stop. Current State is - "
Write-Host $ServiceState.Status
}
}