Restart windows service from service

Simplest way to restart service on a remote computer

What’s the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn’t matter as long as it doesn’t require human interaction.

11 Answers 11

As of Windows XP, you can use sc.exe to interact with local and remote services. Schedule a task to run a batch file similar to this:

Make sure the task runs under a user account privileged on the target server.

psservice.exe from the Sysinternals PSTools would also be doing the job:

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

EXAMPLE: sc start MyService

If it doesn’t require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START

or if you want to get a little more sophisticated, you could try Powershell

There will be so many instances where the service will go in to «stop pending».The Operating system will complain that it was «Not able to stop the service xyz.» In case you want to make absolutely sure the service is restarted you should kill the process instead. You can do that by doing the following in a bat file

To find out which process is associated with your service, go to task manager—> Services tab—>Right Click on your Service—> Go to process.

Note that this should be a work around until you figure out why your service had to be restarted in the first place. You should look for memory leaks, infinite loops and other such conditions for your service to have become unresponsive.

Programmatically restart a Windows Service

I know this can be done in C#/.Net but I was wondering whether it can be done calling the Windows API?

I have a service which will service DHCP requests, when I want to update the configuration for the service I need to stop the service, rewrite its INI file and then start the service again.

Any help appreciated!

8 Answers 8

  1. Open the service control manager with OpenSCManager.
  2. Open the service you want to control with OpenService.
  3. Use ControlService or ControlServiceEx with a SERVICE_CONTROL_STOP parameter to stop the service.
  4. Do whatever you need to do.
  5. Use StartService to restart the service.
  6. Use CloseServiceHandle to close the service and SCM handles.

Sometimes you want to restart the service from the service itself. This solution worked for me. I omitted the rather trivial timer code for clarity. Note that this solution works only because the caller is a service and runs at an elevated level.

Читайте также:  Как сохранить дамп памяти windows

Are you looking for something like this: Starting and stopping services ?

You’ll need to open the service control manager (OpenSCManager), then open the service itself (OpenService) and finally ask it to start itself (StartService). Close off all the handles you’ve used along the way, then you’re done.

Wow, handling services in C++ really takes me back.

I’m late for the party, but I’d suggest the official detailed examples for both starting and stopping a service. The advantage over the other answers here is that they include error handling, edge cases and dependent services —

In a dos box, net start [service] would do what you need. If you don’t find an API solution, you could always start a process for net.exe using start [service] as parameters.

You can also use WMI for this. The sample code at that link is VB, but it should be pretty easy to port to just about any language on Windows.

If you are into automation on Windows, WMI is good to learn because it provides a language-neutral object-oriented interface to most of the interesting objects on the system.

Not the answer you’re looking for? Browse other questions tagged c++ windows-services or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How do I restart a Windows service from a script?

I have a batch script that looks like:

it errors out because sc doesn’t wait till the service is stopped. How do I restart a service with a script?

8 Answers 8

The poster wants to ensure the service is stopped before trying to restart it. You can use a loop on the output of «sc query» doing something like this:

May be missing something, but I use this all the time:

net stop «myservice»
net start «myservice»

net stop «myservice» && net start «myservice»

Dead simple with powershell:

Even better, using display names:

Get-Help Restart-Service for more

If it is purely for restarting the service, you can use

However, if you want access to the options of sc, you can use the start /wait command

this technique is a more general solution that can be applied to any command.

To have quiet restart of some service, which asks confirmations to be stopped (as Server service, for example), You could add /y to the end of stop command.

It would be helpful for automatic script execution.

If you want to restart a failed service you do not need to run a script. In the services MMC snapin right click on a service, select properties, click the recovery tab. Here you can set what actions you want taken should the service stop. There is alot of flexibility available. You will need a script if y ou are trying to stop the service , do something then start the script, preface the batch file with net stop «myserviceshortname» and end with net start «myserviceshortname»

Читайте также:  Где находится удаленный помощник windows

In vbscipt it’s a little more code to stop a service and its’ dependants:

Here’s starting a service and anything it depends on (this should be familiar)

Restarting a Windows service from a Linux box

We have a crummy legacy Windows application (already discussed here) which replicates content to from a Windows host to many Linux hosts. We several instances of it running on several boxes. Each instance has its own .ini file containing a list destination servers. Fairly often we need to change the content of these files and restart the process, a process which is done by hand by our ops team. I’d like to replace this with a simple web-based utility (running on a Linux host) which allows users to generate the configuration files, send them to the hosts and restart the services. Generating the files is easy — I’d probably use Perl and Template Toolkit — and since the servers export their configuration directories copying the data is relatively easy as well.

What’re my options for restarting the Windows services? Win32::Service ? I haven’t had a chance to look very far yet so if you say » x::y makes this easy, but watch out for z» you’d save me a lot of time. Is it even possible? Alternatively, perhaps you could suggest a better way to tackle this problem (replacing the software sadly is not one!) I’m not trying to be lazy, just avoid wasting time fiddling with modules that might not do what I want.

7 Answers 7

Ubuntu includes a utility that can help with managing Windows systems, wmic — WMI Client . With proper permissions, WMI can easily stop and start Windows services.

(An example from the man page, not on service control.)

wmic -U [domain/]adminuser%password //host «select * from Win32_ComputerSystem»

Winexe can do this; it’s the Linux equivalent to Sysinternal’s very useful PsExec tool.

The last time I used Winexe was a couple of years ago, so this may have changed, but at the time, there were a couple of caveats:

  • Terminal handling wasn’t well implemented, so typing non-alphanumeric keys to a remote command may be weird. If you’re scripting, this shouldn’t be an issue.
  • Like PsExec, Winexe operates by installing a service on the Windows box then telling that service to run a command. Unlike PsExec, it didn’t clean the service up afterward. The installed service is harmless and doesn’t run when Winexe isn’t doing anything, so this is pretty much harmless.

Stop and Start a service via batch or cmd file?

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)?

16 Answers 16

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

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

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

Читайте также:  Pdf reader для windows server 2016

As a bat file, error.bat :

The output looks like this:

Return Codes

Edit 20.04.2015

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.

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

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

Instead of checking codes, this works too

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.

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

Syntax always gets me. so.

Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver

In this case. p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.

For your Service Ops junkies. be sure to append your reason code and comment! i.e. ‘4’ which equals ‘Planned’ and comment ‘Stopping server for maintenance’

We’d like to think that «net stop » will stop the service. Sadly, reality isn’t that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won’t know, though, unless you check errorlevel.

The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

I’m seeing the first service take a long time to stop, then the «net stop» for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still «Started» — no change to «Stopping». Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

Оцените статью