How to check if a windows service is installed, if you are starting the service via batch file

Asked

Viewed 2,948 times

5

I need to run a service for some processes, but first I needed to check if 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 myself already installed, it gives an error and I didn’t want it to appear, so I wanted the bat file itself to be able to check if the service is installed.

Check if it’s running, stop 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 anyone has an idea how to fix it I’d appreciate it.

2 answers

2


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

If the service name passed as parameter is not installed the error code 1060 will be shown, from there we can use this error code to do the check.

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: https://technet.microsoft.com/pt-br/library/dd228922(v=Ws.10). aspx

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
  • Thanks for the suggestion was of great help. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.