tags:

views:

4254

answers:

6

I would like to be able to query whether or not a service is running from a windows batch file. I know I can use:

sc query "ServiceName"

but, this dumps out some text. What I really want is for it to set the errorlevel environment variable so that I can take action on that.

Do you know a simple way I can do this?

UPDATE
Thanks for the answers so far. I'm worried the solutions that parse the text may not work on non English operating systems. Does anybody know a way around this, or am I going to have to bite the bullet and write a console program to get this right.

+5  A: 
sc query "ServiceName" | find "RUNNING"
Igal Serban
A: 

Try

sc query state= all

for a list of services and whether they are running or not.

Galwegian
+1  A: 

Hi,

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end
I don't seem to have grep on my system. Did you download it from somewhere, if so, where?
Scott Langham
http://unxutils.sourceforge.net/
Rob Kennedy
I've used something like this, but with a 'find' instead of a 'grep' because I don't want to have to rely on installing anything else.
Scott Langham
A: 

I've found this:

sc query "ServiceName" | findstr RUNNING

seems to do roughly the right thing. But, I'm worried that's not generalized enough to work on non-english operating systems.

Scott Langham
If you really need to do i18n, you should write an app which queries and sets the errorlevel.
hometoast
+2  A: 

You could use wmic with the /locale option

call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
if %ErrorLevel% EQU 0 (
    echo Running
) else (
    echo Not running
)
NicJ
A: