批处理文件禁用服务

批处理文件禁用服务

这是我的批处理文件的片段。我需要确定服务是否存在,如果正在运行,则停止它,并将其更改为禁用,这只需一行代码即可。

echo.&echo.&echo =====Disable services=====
echo.
for %%x in (
"Mcx2Svc"   
"NetTcpPortSharing" 
"RemoteRegistry"
"SharedAccess"
"fax"
"TabletInputService"
"RemoteAccess"
"UxSms"
"Bdesvc"
"EFS"
"wsearch"
"ehsched"
"ehRecvr"
) do (sc query %%x| find "STATE" >nul 2>&1 && sc query %%x| find "RUNNING" >nul 2>&1 && echo Changing services to disabled: %%x && sc config %%x start= disabled)

答案1

堆叠的 sc 查询和查找对我来说毫无意义。即使没有一行好代码,在我看来这也更清晰。

@Echo off
echo.&echo.&echo =====Disable services=====
echo.
for %%x in (
  "Mcx2Svc"   
  "NetTcpPortSharing" 
  "RemoteRegistry"
  "SharedAccess"
  "fax"
  "TabletInputService"
  "RemoteAccess"
  "UxSms"
  "Bdesvc"
  "EFS"
  "wsearch"
  "ehsched"
  "ehRecvr"
) do For /f "tokens=1-3 delims=: " %%S in (
  'sc query %%x ^|findstr /i "STATE" 2^>^&1 '
) Do (
  echo Changing services to disabled: %%x %%S %%T %%U
  Echo sc config %%x start= disabled
)

for /f 解析 sc query 的输出并过滤带有 STATE 的行,存储到变量 %%S、%%T、%%U 中。
要显示将要执行的内容,sc config 前面有一个 echo。删除 echo 以激活该命令。

相关内容