Check if service is running without using Find command
Solution 1
Your code will work fine, if you aren't using Windows NT version 3.1 and Windows NT Advanced Server version 3.1
and your service name doesn't include running
.
Perhaps it is within a loop and so you should use this (or delayed expansion):
sc query "serviceName" | find /i "RUNNING"
if not ERRORLEVEL 1 (
echo serviceName is running.
) else (
echo serviceName is not running
)
Solution 2
You could use Findstr
instead of Find
command:
sc query "Service name" | findstr /i "RUNNING" 1>nul 2>&1 && (
echo serviceName is running.
) || (
echo serviceName is not running
)
You can do it also using wmic
command:
wmic service where name="Service name" get State | Findstr /I "Running" 1>NUL 2>&1 && (
echo serviceName is running.
) || (
echo serviceName is not running
)
Another thing to notice for the future is that when comparing numeric values you should not enclose expressions with quotes ""
, so the condition should look like this:
If %ERRORLEVEL% EQU 0 () ELSE ()
Solution 3
Works for me.Is it possible your ERRORLEVEL variable to be overwriten or your code to be in brackets block? try one of these:
sc query "serviceName" | findstr /i "RUNNING"
if not errorlevel 1 (
echo serviceName is running.
) else (
echo serviceName is not running
)
or
sc query "serviceName" | findstr /i "RUNNING" && (
echo serviceName is running.
goto :skip_not_w
)
echo serviceName is not running
:skip_not_w
The cited bug is for windows nt
(is this your OS?) and should be fixed already...If your os is NT , you should parse the output of the command with FOR /F
to see it contains RUNNING
or use FINDSTR
Solution 4
for /F "tokens=3 delims=: " %%H in ('sc query "serviceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
echo Service not started
net start "serviceName"
)
)
Solution 5
Another way with a function:
:IsServiceRunning servicename
sc query "%~1"|findstr "STATE.*:.*4.*RUNNING">NUL
Usage Example:
Call :IsServiceRunning service && Service is running || Service isn't running
dushyantp
Updated on June 08, 2022Comments
-
dushyantp almost 2 years
In a batch file I'm trying to check if a service is started, if not then wait.
Now to check if a service is running, I am doing this:
sc query "serviceName" | find /i "RUNNING" if "%ERRORLEVEL%"=="0" ( echo serviceName is running. ) else ( echo serviceName is not running )
Trouble is the errorlevel is always set to 0. Possibly because of this known Find bug. Is there any alternate way to check if a service is started, if not then wait?
-
npocmaka over 10 yearsaah.Brackets block.Didn't come to me.+1