Search code examples
tomcatservicebatch-filecmd

Remove/Install windows services using batch


I've got a service called serv1 which I don't know it's state (already installed or not), this service gets installed via another batch file (service.bat install)

My goal is to write a .bat file which checks if serv1 exists, so I want to remove it and re-create it calling 'service.bat install' ; if not, create it calling 'service.bat install'

I've searched for some commands; I found that we use " sc delete ServiceName but, I'm not familiar with batch a lot.


Solution

  • I hope the following bat script will help you out. Open notepad; copy the following code and paste it in notepad. Save the file with .bat extension e.g. "Helper.bat".

    Now open command prompt, navigate to the directory where Helper.bat (and your service.bat) are placed. Then write a command like this Helper.bat serv1

    This is a generic script so you need to pass the concerned service name as a parameter. Otherwise simply replace %1 with serv1 and get your work done!

    If you need to know more about this script then feel free to ask me.

    Here's the script:

    @echo off
    sc query %1
    IF ERRORLEVEL == 1060 GOTO NOT_EXIST
    
    :Exist
        cls
        echo %1 already exist.
        SET /P result=Do you want to delete and reinstall the service? (Press Y or N)
    
        IF %result% == Y
                GOTO REINSTALL_SERVICE
    
        IF %result% == N
                GOTO End
    
    GOTO End
    
    :NOT_EXIST
        cls
        echo Service does not exist. Going to install now
        GOTO INSTALL_SERVICE
    
    :REINSTALL_SERVICE
        sc delete %1
        GOTO INSTALL_SERVICE
    
    :INSTALL_SERVICE:
        call service.bat install
        echo Installation Completed!
    
    :End
        pause