how to check if the services stopped

2019-09-06 16:46发布

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?

1条回答
冷血范
2楼-- · 2019-09-06 17:20

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.

查看更多
登录 后发表回答