Q. How can I start a service only if a specified service is already started?

If you know the Display Name of the service that must be started, you can conditionally start a service based upon the started status of another service by using the following commands:

for /f "Tokens=*" %%a in ('net start^|Find /i "Display Name of Service that must already be started"') do (
  net start "Display name or short name of the service you wish to start"
)
If you are not sure that you have the Display Name or the service short name, its' registry key, use CSSvc.bat. The syntax for using CSSvc.bat is:

CSSvc StartSvc IfSvc OK

Where:

StartSvc is the short or Display Name of the service you wish to start.

IfSvc    is the short or Display Name of the service that must already be started.

OK       is a call directed environment variable that will contain:
         Y if StartSvc was successfully started.
         N if StartSvc failed to start, or if a service was not found, or if StartSvc EQUAL IfSvc.
         A if StartSvc was already started.
NOTE: CSSvc.bat uses SvcDnSnRpt.bat, which must be located in a folder that is in your PATH.

CSSvc.bat contains:

@echo off
setlocal EnableDelayedExpansion
if \{%3\}==\{\} goto err1
set StartSvc=%1
set IfSvc=%2
set SS=N
set IS=N
set StartSvc="%StartSvc:"=%"
set IfSvc="%IfSvc:"=%"
for /f "Tokens=1* Delims=," %%s in ('SvcDnSnRpt') do (
 If /i !StartSvc! EQU %%s set SS=Y
 If /i !StartSvc! EQU %%t set SS=Y&set StartSvc=%%s
 If /i !IfSvc! EQU %%s set IS=Y
 If /i !IfSvc! EQU %%t set IS=Y&set IfSvc=%%s
)
if "%SS%" EQU "N" goto  err3
if "%IS%" EQU "N" goto  err4
if /i %StartSvc% EQU %IfSvc% goto err2
set OK=N
for /f "Tokens=*" %%a in ('net start^|find /i %StartSvc%') do (
 set OK=A
)
if "%OK%" EQU "A" goto AOK
for /f "Tokens=*" %%a in ('net start^|Find /i %IfSvc%') do (
  call :quiet>nul 2>&1
)
if %ERRORLEVEL% EQU 0 set OK=Y
:AOK
endlocal&set %3=%OK%
goto :EOF
:err1
@echo Syntax: CSSvc StartSvc IfSvc OK
endlocal
goto :EOF
:err2
@echo Syntax: CSSvc -  %StartSvc%=%IfSvc%
endlocal&set %3=N
goto :EOF
:err3
@echo Syntax: CSSvc -  %StartSvc% not found.
endlocal&set %3=N
goto :EOF
:err4
@echo Syntax: CSSvc -  %IfSvc% not found.
endlocal&set %3=N
goto :EOF
:quiet
net start %StartSvc%


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish