Stop and Start a service via batch or cmd file?

879,836

Solution 1

Use the SC (service control) command, it gives you a lot more options than just start & stop.

  DESCRIPTION:
          SC is a command line program used for communicating with the
          NT Service Controller and services.
  USAGE:
      sc <server> [command] [service name]  ...

      The option <server> has the form "\\ServerName"
      Further help on commands can be obtained by typing: "sc [command]"
      Commands:
        query-----------Queries the status for a service, or
                        enumerates the status for types of services.
        queryex---------Queries the extended status for a service, or
                        enumerates the status for types of services.
        start-----------Starts a service.
        pause-----------Sends a PAUSE control request to a service.
        interrogate-----Sends an INTERROGATE control request to a service.
        continue--------Sends a CONTINUE control request to a service.
        stop------------Sends a STOP request to a service.
        config----------Changes the configuration of a service (persistant).
        description-----Changes the description of a service.
        failure---------Changes the actions taken by a service upon failure.
        qc--------------Queries the configuration information for a service.
        qdescription----Queries the description for a service.
        qfailure--------Queries the actions taken by a service upon failure.
        delete----------Deletes a service (from the registry).
        create----------Creates a service. (adds it to the registry).
        control---------Sends a control to a service.
        sdshow----------Displays a service's security descriptor.
        sdset-----------Sets a service's security descriptor.
        GetDisplayName--Gets the DisplayName for a service.
        GetKeyName------Gets the ServiceKeyName for a service.
        EnumDepend------Enumerates Service Dependencies.

      The following commands don't require a service name:
      sc <server> <command> <option>
        boot------------(ok | bad) Indicates whether the last boot should
                        be saved as the last-known-good boot configuration
        Lock------------Locks the Service Database
        QueryLock-------Queries the LockStatus for the SCManager Database
  EXAMPLE:
          sc start MyService

Solution 2

net start [serviceName]

and

net stop [serviceName]

tell you whether they have succeeded or failed pretty clearly. For example

U:\>net stop alerter
The Alerter service is not started.

More help is available by typing NET HELPMSG 3521.

If running from a batch file, you have access to the ERRORLEVEL of the return code. 0 indicates success. Anything higher indicates failure.

As a bat file, error.bat:

@echo off
net stop alerter
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause

The output looks like this:

U:\>error.bat
The Alerter service is not started.

More help is available by typing NET HELPMSG 3521.

There was a problem
Press any key to continue . . .

Return Codes

 - 0 = Success
 - 1 = Not Supported
 - 2 = Access Denied
 - 3 = Dependent Services Running
 - 4 = Invalid Service Control
 - 5 = Service Cannot Accept Control
 - 6 = Service Not Active
 - 7 = Service Request Timeout
 - 8 = Unknown Failure
 - 9 = Path Not Found
 - 10 = Service Already Running
 - 11 = Service Database Locked
 - 12 = Service Dependency Deleted
 - 13 = Service Dependency Failure
 - 14 = Service Disabled
 - 15 = Service Logon Failure
 - 16 = Service Marked For Deletion
 - 17 = Service No Thread
 - 18 = Status Circular Dependency
 - 19 = Status Duplicate Name
 - 20 = Status Invalid Name
 - 21 = Status Invalid Parameter 
 - 22 = Status Invalid Service Account
 - 23 = Status Service Exists
 - 24 = Service Already Paused

Edit 20.04.2015

Return Codes:

The NET command does not return the documented Win32_Service class return codes (Service Not Active,Service Request Timeout, etc) and for many errors will simply return Errorlevel 2.

Look here: http://ss64.com/nt/net_service.html

Solution 3

You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.

net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%

Disclaimer: I've written this from the top of my head, but I think it'll work.

Solution 4

Instead of checking codes, this works too

net start "Apache tomcat" || goto ExitError

:End  
exit 0  

:ExitError  
echo An error has occurred while starting the tomcat services  
exit 1  

Solution 5

I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit. I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.

The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.

If I am wrong, anyone can feel free to correct me on this.

@echo off
set /p c= Would you like to start a service [Y/N]?
  if /I "%c%" EQU "Y" goto :1
  if /I "%c%" EQU "N" goto :2
    :1  
    set /p var= Service name: 
:2 
set /p c= Would you like to stop a service [Y/N]?
  if /I "%c%" EQU "Y" goto :3
  if /I "%c%" EQU "N" goto :4
    :3  
    set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
  if /I "%c%" EQU "Y" goto :5
  if /I "%c%" EQU "N" goto :6
    :5  
    set /p var2= Service name:
:6 
set /p c= Would you like to set a service to auto [Y/N]?
  if /I "%c%" EQU "Y" goto :7
  if /I "%c%" EQU "N" goto :10
    :7  
    set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto
Share:
879,836

Related videos on Youtube

Keng
Author by

Keng

Personal Achievables: Medical Note: I now have irreversible damage to my kidneys and liver after having used this site.

Updated on March 11, 2022

Comments

  • Keng
    Keng about 2 years

    How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?

    • user1149201
      user1149201 over 15 years
      Maybe somewhat offtopic (since you ask for bat & cmd instruction) but: PowerShell gives you a lot of control and feedback for doing actions like this.
  • Tim Frey
    Tim Frey over 15 years
    I agree that this is better than net start/stop. Note that there is an option to touch services on remote machines as well.
  • Wernight
    Wernight almost 12 years
    NET is not just for service related functions whilst SC is just for service related functions.
  • Michael K.
    Michael K. over 10 years
    Great answer. But you need to be administrator to run 'SC start service'. I found a solution for that here.(The accepted answer contains the solution)
  • Dom
    Dom over 10 years
    The problem with SC is that the command returns immediately and not after the action is complete. If you want to restart a service via batch file (stop then start), the stop returns immediately, the start then fails because the service isn't stopped. Net stop/start returns after the action is complete, so doesn't have this problem.
  • Frantumn
    Frantumn over 9 years
    How do I do this if I need to use another user ID and password to log on ?
  • user4317867
    user4317867 about 9 years
    You run CMD as the other user/ID by doing runas /user:Domain\UserName cmd then enter your password. CMD will start running as the specified user account.
  • James Parsons
    James Parsons almost 9 years
    Typically, code only answers are not appreciated. Could you elaborate on your solution or add some explanatory comments?
  • Nathanial Wilson
    Nathanial Wilson almost 9 years
    I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you.
  • Steven
    Steven about 8 years
    This answer is better because "net" command blocks and wait for the service to start or stop before the batch script continues executing.
  • Victor Zakharov
    Victor Zakharov over 7 years
    The linked page no longer exists. As such, this is more of a comment now.
  • Satish Singh
    Satish Singh almost 7 years
    I opened the cmd as administrator mode, getting error The syntax of this command is: NET STOP service
  • OfirD
    OfirD about 4 years
    Since (as the Edit says) most of the time the errorlevel returned is 2, see here how to interpret the error result.
  • Anand Varkey Philips
    Anand Varkey Philips almost 4 years
    is there a way to check if service is stopped properly?? in 2020?
  • Romil Kumar Jain
    Romil Kumar Jain over 2 years
    why sc delete always?