如何检查服务是否通过批处理文件运行,启动它,如果它没有运行? [英] How to check if a service is running via batch file and start it, if it is not running?

查看:424
本文介绍了如何检查服务是否通过批处理文件运行,启动它,如果它没有运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


  • 检查服务是否运行结果

    • 如果是运行,退出批

    • 如果它没有运行,启动服务


在code样品我GOOGLE至今竟然没有工作,所以我决定不张贴。

启动服务是由完成的:

 网​​络启动SERVICENAME


  1. 如何检查服务是否运行,以及如何使一个if语句在批处理文件?

  2. 我有点困惑。什么是我需要传递到网络启动的说法?该服务名称或显示名称?


解决方案

要检查服务的状态,使用 SC查询<&SERVICE_NAME GT; 。因为如果在批处理文件块,查看文档

以下code将检查服务的状态服务名并启动它,如果它没有运行(中频如果服务不是块将被执行运行):

  FOR / F令牌= 3 delims =%%的H(SC查询服务名^ | FINDSTR国家')做(
  如果/ I%% HNEQRUNNING(
   REM把你的code你想在这里执行
   REM例如,下面的行
   NET START服务名
  )

是做什么的说明:


  1. 查询服务的属性。

  2. 查找包含文本国家行

  3. Tokenizes那行,翻出第三个符号,它是包含服务的状态之一。

  4. 测试对字符串RUNNING结果状态

至于你的第二个问题,参数,你会想传递给网​​络启动是服务名称,的的显示名称。

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.

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?

解决方案

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

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

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"

As for your second question, the argument you will want to pass to net start is the service name, not the display name.

这篇关于如何检查服务是否通过批处理文件运行,启动它,如果它没有运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆