How would you check if a WIN32 service exists and, if so, do some operation?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With