I would like to know how to check if a service is running using a batch file
e.g.
if xxxx service is running go to start stage2.bat else go to echo Service not running
Any help would be appreciated
Thanks
I would like to know how to check if a service is running using a batch file
e.g.
if xxxx service is running go to start stage2.bat else go to echo Service not running
Any help would be appreciated
Thanks
Similar to How to check if a process is running via a batch script
EDIT:
From the post, with an added else statement:
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" (
call stage2.bat
) else (
echo Program is not running
)
For a service:
sc query "ServiceName" | find "RUNNING"
if "%ERRORLEVEL%"=="0" (
call stage2.bat
) else (
echo Program is not running
)
read this article http://support.microsoft.com/kb/251192 and see SC /?
then try
SC QUERY
EDIT: to automate the check, pipe the result to FIND and look for RUNNING
SC QUERY %1 | FIND "STATE" | FIND "RUNNING" >nul
IF ERRORLEVEL 1 (echo NOT RUNNING ) ELSE (echo RUNNING)
My solution, because under Windows7 just IF ERRORLEVEL 1
does not work and errorlevel is 0 in case findstr
successful or not.
In my case, I'm looking for something started by java.exe, lets say HELLO.jar [parameter of java.exe]
wmic PROCESS LIST FULL | findstr /I java.exe | findstr /I HELLO.jar
if ErrorLevel 1 (
Echo OK
msg "%username%" HELLO.jar not started
Pause
) else (
Echo ERR
msg "%username%" HELLO.jar already running
Pause
exit
)
First of all you might need admin privileges and non of the examples deals with that. If you don't make us of nircmd already you could start now 🤪
This is how I do it anyways. When my bluetooth stops working 😬
set _ServiceName=CSRBtAudioService
call :SrvStat %_ServiceName%
goto :SomeWhere
:SrvStat
sc query "%1" | find "RUNNING"
if %Errorlevel% EQU 0 ( echo: restarting %1 & nircmd elevatecmd service restart %1
) else ( echo: starting %1 & nircmd elevatecmd service start %1 )
exit /b
In case someone is looking to do this on a remote system using SC. Note: Placed in the extra 'if /I "%%H"' statement for example purposes of further use.
SC \\host query
Example:
:: This example prints the status of a remote service
SC \\%REMOTE_SYSTEM% query %SERVICE% | FIND "STATE" >nul
IF ERRORLEVEL 1 (
echo RESULT: %SERVICE% is [UNKNOWN]
) ELSE (
for /F "tokens=3 delims=: " %%H in ('SC \\%REMOTE_SYSTEM% query "%SERVICE%" ^| findstr " STATE"') do (
if /I "%%H"=="STOPPED" (
echo RESULT: %SERVICE% is %%H
) else (
echo RESULT: %SERVICE% is %%H
)
)
)