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

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

问题描述

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

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

  • 检查服务是否正在运行
    • 如果正在运行,则退出批处理
    • 如果没有运行,启动服务

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

    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. 如何检查服务是否正在运行,以及如何在批处理文件中创建 if 语句?
    2. 我有点困惑.我必须传递到网络开始的论点是什么?服务名称或其显示名称?

    推荐答案

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

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

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

    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"
      )
    )
    

    解释它的作用:

    1. 查询服务的属性.
    2. 查找包含文本STATE"的行
    3. 标记该行,并提取第三个标记,即包含服务状态的标记.
    4. 根据字符串RUNNING"测试结果状态

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

    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天全站免登陆