检查Windows服务是否自动

时间:2019-01-23 15:56:19

标签: batch-file windows-services

我正在尝试创建一个批处理脚本,以查看Windows服务(例如)。 wuauserv设置为自动启动。到目前为止,我已经尝试过

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

但这仅显示我的运行状态,我想知道是否将其设置为自动启动。检查状态的IF语句的加分。

解决方案 这是我设计的解决方案,这要归功于以下人员和SO方面的其他人员。 随时对this GitHub Gist

进行改进
@ECHO OFF 
ECHO This script re-enables Windows Update and sets it to Automatic. 
ECHO However, this script needs to be run as admin.
net.exe session 1>NUL 2>NUL || goto :not_admin
echo Sucess! You ran this script with Admin rights!
sc qc "wuauserv" | findstr /i AUTO_START > nul
goto :check

:check
if %ERRORLEVEL% equ 0 ( 
    ECHO The service is set to start automatically. 
    TIMEOUT 5
) ELSE ( 
    echo The service is NOT set to start automatically. Trying again. 
    sc config "wuauserv" start= auto
    net start wuauserv
    goto :check
) 
exit


:not_admin
echo ERROR: please run as admin 
TIMEOUT 10 /nobreak
exit 

2 个答案:

答案 0 :(得分:0)

尝试此批处理文件,该文件将服务名称作为参数,如果自动,则返回0,否则返回1:

@echo off

if [%1]==[] (
  echo Missing service name. Returning 2.
  exit /b 2
)

sc qc "%1" | findstr /i AUTO_START > nul

if %ERRORLEVEL% equ 0 (
  echo The "%1" service is set to start automatically. Returning 0.
  exit /b 0
) else (
  echo The "%1" service is NOT set to start automatically ^(or the service is inaccessible^). Returning 1.
  exit /b 1
)

答案 1 :(得分:0)

通过WMIC使用win32_service的替代选项:

WMIC Service Where "Name='wuauserv' And StartMode='Auto'" Get State /Value 2>Nul|Find "State="||Echo Service is not set to Auto

如果您想更改启动模式,如果不将其设置为自动,则也可以将其作为一个命令来完成:

WMIC Service Where "Name='wuauserv' And StartMode!='Auto'" Call ChangeStartMode "Auto"