0

I have done a batch file that stop the services, delete files, install files, and start the services. till now it didn't have any trouble. but today it failed to install the files.

After a little search I have seen that the services are on stopping and not on stopped. I am using net stop "Service-Name" to stop the services.

How can I check when the services are stopped or wait for them to completely stop?

elad
  • 35
  • 1
  • 5
  • See answers to http://stackoverflow.com/questions/133883/stop-and-start-a-service-via-batch-or-cmd-file or [How to check the exit code of the last command in batch file][1]. [1]: http://superuser.com/questions/194662/how-to-check-the-exit-code-of-the-last-command-in-batch-file – Mogsdad Mar 03 '13 at 19:20

1 Answers1

1

wmic service where name="Service-Name" get state will show you whether a service is running or stopped. You can loop back to that command and use a ping to pause.

:running
ping /n 2 0.0.0.0 >NUL
for /f "tokens=2 delims=^=" %%I in ('wmic service where name^="Service-Name" get state /format:list') do (
    if #%%I==#Running goto running
)
rem When the script reaches this line, the service status is not "Running."

Or if you prefer using sc to determine the state of a service:

:running
ping /n 2 0.0.0.0 >NUL
for /f "tokens=4" %%I in ('sc query Service-Name ^| find /i "state"') do (
    if #%%I==#RUNNING goto running
)
rem When the script reaches this line, the service status is not "Running."

I'm not certain, but it's possible that a service could say "stopped" when it's actually "stopping", or "running" when it's actually "starting." If that's the case, then you might be better off checking whether a process exists in the process list. That can also be done using wmic: wmic process where name="appname.exe" get name or similar.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • this code : sc query Service-Name ^| find /i "state" was extremely helpful. thank you very much. – elad Mar 05 '13 at 08:08