【问题标题】:Batch program to stop services that are running停止正在运行的服务的批处理程序
【发布时间】:2012-02-15 23:50:07
【问题描述】:

假设我有一个以名称“MyServiceFactory -”开头的服务列表。并非所有这些都会启动,只有少数会启动,并且会因服务使用情况而异。我正在寻求帮助编写一个批处理程序,该程序只停止正在运行的服务并启动这些服务(不是所有服务并且不重新启动)。任何帮助表示赞赏

【问题讨论】:

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


    【解决方案1】:

    您也可以尝试使用 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 用于提及 PS。 PS 中大致等效的 1-liner 将是:get-wmiobject win32_service -filter "name like 'srv_name_pattern' and state='Running'"| foreach { stop-service $_.name; start-service $_.name}
    【解决方案2】:

    这应该可以工作(或者至少给你一个开始):

    @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 - 这将显示所有服务、它们的标题、显示名称和状态。直接从批处理运行第一个查询,直到获得所需的结果,根据需要进行更改,然后调整批处理。
    • @G33kKahuna 抱歉忘了给你发之前的地址...看看,应该有帮助
    • 感谢 wmz.. 你的代码让我通过了,我想出了我的 wmic 命令行。这有帮助。 powershell 暂时禁止使用
    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多