As I verify if a windows service is installed, if it is to start the service via batch file

4

I need to run a service for some processes, but first I need to verify that the service is installed.

The commands I use to install and uninstall are as follows:

%DIRServico%\SERVICO.EXE /INSTALL
%DIRServico%\SERVICO.EXE /UNINSTALL

If I try to install it already installed, it gives an error and I did not want it to appear, so I wanted the bat file itself to be able to check if the service is installed.

Check if it is running, stopped I already have the commands.

NET START | FINDSTR "Servico"

if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo comando desconhecido
goto end    
:started
NET STOP Servico
goto end
:stopped
NET START Servico
goto end
:end

If someone has an idea how to solve it, I appreciate it.

    
asked by anonymous 13.04.2017 / 16:55

2 answers

2

The SC QUERY command displays information about a particular service, shows type, status, etc.

If the service name passed as a parameter is not installed, error code 1060 will be displayed, and we can then use this error code to perform the verification.

Adapt to your code:

@echo off

rem Nome do seu serviço:
set ServiceName=Servico

SC QUERY %ServiceName% > NUL
IF ERRORLEVEL 1060 GOTO nao

rem Comandos para rodar caso o serviço esteja instalado:
ECHO Servico instalado!
GOTO fim

:nao
rem Comandos para rodar caso o serviço não esteja instalado:
ECHO Servico nao instalado!


:fim
pause

For more information: link

    
13.04.2017 / 17:59
0

Below is a suggestion using the native program sc , used for communication with the Windows Service Manager.

@echo off
    setlocal EnableDelayedExpansion
    set SERVICE_NAME=myservice
rem Verifica se o serviço está rodando
    echo Verificando se o %SERVICE_NAME% está instalado
    sc query %SERVICE_NAME% | find /i "%SERVICE_NAME%"
rem Se existe o serviço
    if "%ERRORLEVEL%"=="0" (
       goto :Fim
    )
    echo Instalando o serviço %SERVICE_NAME%
    sc create %SERVICE_NAME% start= auto binPath= "C:\mylocation\%SERVICE_NAME%" DisplayName= "%SERVICE_NAME%"
rem Inicia o serviço
    echo Iniciando o serviço %SERVICE_NAME%
    sc start %SERVICE_NAME%
    goto :Fim
rem
rem Finalização
:Fim
    endLocal
    
13.04.2017 / 18:54