【发布时间】:2012-02-15 23:50:07
【问题描述】:
假设我有一个以名称“MyServiceFactory -”开头的服务列表。并非所有这些都会启动,只有少数会启动,并且会因服务使用情况而异。我正在寻求帮助编写一个批处理程序,该程序只停止正在运行的服务并启动这些服务(不是所有服务并且不重新启动)。任何帮助表示赞赏
【问题讨论】:
标签: windows-7 batch-file windows-server-2008-r2 windows-scripting
假设我有一个以名称“MyServiceFactory -”开头的服务列表。并非所有这些都会启动,只有少数会启动,并且会因服务使用情况而异。我正在寻求帮助编写一个批处理程序,该程序只停止正在运行的服务并启动这些服务(不是所有服务并且不重新启动)。任何帮助表示赞赏
【问题讨论】:
标签: windows-7 batch-file windows-server-2008-r2 windows-scripting
您也可以尝试使用 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 那样为您提供服务正在发生的情况的状态,但您必须喜欢简洁 :)
【讨论】:
get-wmiobject win32_service -filter "name like 'srv_name_pattern' and state='Running'"| foreach { stop-service $_.name; start-service $_.name}
这应该可以工作(或者至少给你一个开始):
@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 -%"。
【讨论】:
wmic。在 wmic 提示符下,执行 service get name,caption,displayname,state - 这将显示所有服务、它们的标题、显示名称和状态。直接从批处理运行第一个查询,直到获得所需的结果,根据需要进行更改,然后调整批处理。