tags:

views:

121

answers:

3

How would you check if a WIN32 service exists and, if so, do some operation?

+4  A: 

Off the top of my head, you can check if a specific service is running, as mentioned by bmargulies, using the "net" command, piping the result into "find". Something like the following would check if a service was running, and if so stop it. You can then start it without worrying about if it was already running or not:

net start | find "SomeService"
if ERRORLEVEL 1 net stop "SomeService"
net start "SomeService"

If you're using findstr to do a search, as some of the other answers have suggested, then you would check for ERRORLEVEL equal to 0 (zero)... if it is then you have found the string you're looking for:

net start | findstr "SomeService"
if ERRORLEVEL 0 net stop "SomeService"
net start "SomeService"

Essentially most DOS commands will set ERRORLEVEL, allowing you to check if something like a find has succeeded.

icabod
+4  A: 

You can't do this in DOS, as DOS is not Windows and doesn't even have the concept of a "service".

In a Windows batch file you can use the sc command to find services:

sc query | findstr SERVICE_NAME

This will enumerate all services and yield their respecitve names.

You can search for a specific service with

sc query | findstr /C:"SERVICE_NAME: myservice"

Remember that this search is case-sensitive. You can add the /I switch to findstr to avoid that.

Joey
+1  A: 

How about using WMIC:

First list all processes, then grep your process name. No result will be printed if it does not exist.

wmic service |findstr "ProcessName"

Example:

C:\>wmic service |findstr "Search"
FALSE        TRUE        Windows Search
Jay Zeng
how would that work in an if statement?
Burt
@Burt: if statement in what language? batch, vbscript, c# or even perl? Certainly it will be much easier if you install wc (part of coreutils in gnu32), you will do c:>wmic service |findstr "Search"|wc -l, then write some code to grab that number to determine.
Jay Zeng