Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if service is running without using Find command

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?

like image 844
dushyantp Avatar asked Mar 17 '26 14:03

dushyantp


1 Answers

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 ()
like image 183
ElektroStudios Avatar answered Mar 20 '26 06:03

ElektroStudios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!