Domanda

Say i have a list of service all starting with the name "MyServiceFactory -". Not all of them will be started, just a handful and it varies upon service usage. I'm looking for help writing a batch program that only stops services that are running and starts these services (not all services and not restart). Any help is appreciated

È stato utile?

Soluzione

This should work (or at least give you a start):

@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

Assuming you name your batch file batch.bat, you would call it batch.bat "MyServiceFactory -%".

Altri suggerimenti

You can also try using PowerShell. I have some one-liners I use to start and stop our services:

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

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

Downside is the PowerShell command doesn't give you a status on what's happening with the service like net start does, but you gotta love the brevity :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top