0

假设我有一个服务列表,名称均以“MyServiceFactory - ”开头。并非所有的人都会开始,只有少数人会随着服务的使用而变化。我正在寻找帮助编写一个批处理程序,只停止正在运行的服务并启动这些服务(并非所有服务都不重新启动)。任何帮助表示赞赏批处理程序停止正在运行的服务

回答

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

+0

谢谢...我得到“节点”,当我运行上述。我将尝试更多的调试 – G33kKahuna 2012-02-16 03:37:48

+0

这意味着它无法找到任何正在运行的服务和给定的标题(在服务工具中看到的描述性名称)。我认为这是你的名字,因为它包含空间,但也有内部服务名称。最好运行'wmic'。在wmic提示符下,exec'service获取名称,标题,显示名称,状态 - - 这将显示所有服务,它们的标题,显示名称和状态。直接运行批次中的第一个查询,直到获得您想要的结果,并根据需要更改,然后调整批次。 – wmz 2012-02-16 12:28:57

+0

@ G33kKahuna对不起忘了解决以前给你...看看,它应该帮助 – wmz 2012-02-16 13:57:50

2

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

缺点是PowerShell命令不给你上什么是与服务发生像net start做了状态,但你得喜欢简洁:)

+1

+1。在PS中Roughy等价的1-liner会是:'get-wmiobject win32_service -filter'name like'srv_name_pattern'and state ='Running'“| foreach {stop-service $ _。name;开始服务$ _。name}' – wmz 2012-02-16 16:11:31

+0

+1为我完美工作。 – ashes999 2012-03-01 18:25:59

相关问题