6

我想要一个批处理文件来检查服务“MyServiceName”是否正在运行。如果服务正在运行,我希望批处理文件禁用它,然后显示一条消息。如果它没有运行并且被禁用,我希望批处理文件显示一条消息然后退出。谢谢您的帮助。

4

3 回答 3

11
sc query MyServiceName| find "RUNNING" >nul 2>&1 && echo service is runnung
sc query MyServiceName| find "RUNNING" >nul 2>&1 || echo service is not runnung

停止服务:

net stop MyServiceName
于 2013-06-25T13:18:22.957 回答
2

如果试图想出一个使用SC-command 的小脚本,但它似乎有一些限制(我无法测试它):

@echo off
setlocal enabledelayedexpansion
:: Change this to your service name
set service=MyServiceName
:: Get state of service ("RUNNING"?)
for /f "tokens=1,3 delims=: " %%a in ('sc query %service%') do (
  if "%%a"=="STATE" set state=%%b
)
:: Get start type of service ("AUTO_START" or "DEMAND_START")
for /f "tokens=1,3 delims=: " %%a in ('sc qc %service%') do (
  if "%%a"=="START_TYPE" set start=%%b
)
:: If running: stop, disable and print message
if "%state%"=="RUNNING" (
  sc stop %service%
  sc config %service% start= disabled
  echo Service "%service%" was stopped and disabled.
  exit /b
)
:: If not running and start-type is manual, print message
if "%start%"=="DEMAND_START" (
  echo Start type of service %service% is manual.
  exit /b
)
:: If start=="" assume Service was not found, ergo is disabled(?)
if "%state%"=="" (
  echo Service "%service%" could not be found, it might be disabled.
  exit /b
)

我不知道这是否给出了你想要的行为。似乎SC没有列出已禁用的服务。但是由于如果它被禁用你不想做任何事情,我的代码只是在找不到服务时打印一条消息。

但是,您可以希望将我的代码用作您的目的的框架/工具箱。

编辑:

鉴于 npocmaka 的回答,您可能可以将 -sections 更改为for

sc query %service%| find "RUNNING" >nul 2>&1 && set running=true
于 2013-06-25T14:01:52.637 回答
1

此脚本将服务名称作为第一个(也是唯一的)参数,或者您可以将其硬编码到 SVC_NAME 分配中。sc 命令的输出被丢弃。不知道你是不是真的想看。

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET SVC_NAME=MyServiceName
IF NOT "%~1"=="" SET "SVC_NAME=%~1"

SET SVC_STARTUP=
FOR /F "skip=1" %%s IN ('wmic path Win32_Service where Name^="%SVC_NAME%" get StartMode') DO (
    IF "!SVC_STARTUP!"=="" SET "SVC_STARTUP=%%~s"
)

CALL :"%SVC_STARTUP%" "%SVC_NAME%"
CALL :StopService "%SVC_NAME%"
GOTO :EOF

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:"Boot"
:"System"
:"Auto"
:"Manual"
@ECHO Disabling service '%~1'.
sc.exe config "%~1" start= disabled > NUL
IF NOT ERRORLEVEL 1 @ECHO Service '%~1' disabled.
EXIT /B

:"Disabled"
@ECHO Service '%~1' already disabled.
EXIT /B


::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:StopService
SETLOCAL
SET SVC_STATE=
FOR /F "skip=1" %%s IN ('wmic path Win32_Service where Name^="%~1" get State') DO (
   IF "!SVC_STATE!"=="" SET "SVC_STATE=%%~s"
)
CALL :"%SVC_STATE%" "%~1"
EXIT /B


:"Running"
:"Start Pending"
:"Continue Pending"
:"Pause Pending"
:"Paused"
:"Unknown"
@ECHO Stopping service '%~1'.
sc.exe stop "%~1" > NUL
IF NOT ERRORLEVEL 1 @ECHO Service '%~1' stopped.

EXIT /B

:"Stop Pending"
:"Stopped"
@ECHO Service '%~1' is already stopping/stopped.
EXIT /B
于 2013-06-25T14:02:42.203 回答