批处理程序,用于停止正在运行的服务

时间:2012-02-15 23:50:08

标签: windows-7 batch-file windows-server-2008-r2 windows-scripting

假设我有一个名为“MyServiceFactory - ”的服务列表。并非所有这些都将启动,只需少量,并且根据服务使用情况而有所不同。我正在寻找帮助编写批处理程序,只停止正在运行的服务并启动这些服务(不是所有服务而不是重启)。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

您也可以尝试使用PowerShell。我有一些用于启动和停止服务的单行:

# Start all services with FOO in their name:
powershell -Command start-service *FOO*

# Stop all running FOO services:
powershell -Command stop-service *FOO*

下行是PowerShell命令不会为您提供有关net start等服务所发生情况的状态,但您必须喜欢简洁:)

答案 1 :(得分:1)

这应该有效(或至少给你一个开始):

@echo off 
setlocal
if "%~1"=="" goto usage
set tmpFile=templist.txt
set tmpAnsi=templist_ansi.txt
wmic /locale:MS_409 service where "caption like '%~1' and state='Running'"  get caption /format:csv >%tmpFile%
REM this is required to convert from Unicode(UCS-2) to ANSI
type %tmpFile%>%tmpAnsi%

Echo ---------------Stopping services----------------------
Echo.
for /f "tokens=2 skip=2 delims=," %%i  in (%tmpAnsi%) do (
   wmic /locale:MS_409 service where caption="%%i" call stopservice
)

Echo --------------Starting services-----------------------
Echo.
for /f "tokens=2 skip=2 delims=," %%i  in (%tmpAnsi%) do ( 

   wmic /locale:MS_409 service where caption="%%i" call startservice
)

goto end

:usage
Echo.
Echo Usage is: 
Echo %~n0 pattern_to_check
Echo.
Echo Pattern: 
Echo [ ]  Any one character within the specified range ([a=f]) or set ([abcdef]).
Echo ^^    Any one character not within the range ([^a=f]) or set ([^abcdef].)
Echo %%    Any string of 0 (zero) or more characters
Echo _    (underscore) Any one character. Any literal underscore    
Echo         used in the query string must be escaped by placing it inside []
Echo.
Echo     If pattern contains spaces, it must be enclosed in double quotes 

:end

假设您将批处理文件命名为batch.bat,您可以将其命名为batch.bat "MyServiceFactory -%"