Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Service Exists Condition

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

like image 570
Burt Avatar asked Dec 16 '09 16:12

Burt


2 Answers

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.

like image 143
icabod Avatar answered Oct 13 '22 14:10

icabod


Just an addendum to the accepted answer. If you are looking to do other things than just restarting the service, and are looking to see if the service is installed.

sc query state= all | findstr /C:"SERVICE_NAME: MyService" 
if ERRORLEVEL 0 (**My Operation**)

In this case, the state= all is important since if the service is not started, it will be interpreted as not installed, which are two separate things.

like image 36
helios456 Avatar answered Oct 13 '22 16:10

helios456