Windows restart service from cmd

The Core Technologies Blog

Our Software // Windows Services // 24×7 Operation

Essential Tools for Windows Services: The NET Command

If you manage Windows Services and are comfortable working from the command line, then the Windows NET.EXE command should be in your toolkit. Use it to easily start, stop, pause or restart any service from an elevated command prompt, or in a convenient script/batch file.

Using NET to stop a Windows Service

To stop a service, run:

where is the name of the service. Be sure to enclose it in quotes if it contains a space!

For example, to stop the Print Spooler service (named “Spooler”), run:

Here is what it looks like on our Windows Server 2016 computer:

Notice that the NET command will wait for the service to stop before continuing. The only exception is when the service is unresponsive or takes more than 30 seconds to comply.

Starting a Windows Service with NET

To start an idle Windows Service, run:

If all goes well, your service (and any other service it depends on to operate) will be started after a few seconds:

How to Restart a Windows Service with NET.EXE

To restart a service, say from a batch file, chain the “net stop” and “net start” commands together like this:

NET will also Pause and Resume Windows Services

Not all services support pause and resume, but if you have one that does, NET can come in handy there as well.

To pause a service, type:

To resume a paused service, run:

You may also like.

28 Responses to Essential Tools for Windows Services: The NET Command

On using the NET command in a batch to restart I recommend adding time for the services to react. I’ve done this for one of my services that tends to hang. See below;

@ECHO.
@ECHO Stopping services, please wait for 10 seconds…

@ECHO OFF
REM Stop Service

NET STOP ServiceNameHere

REM The following is a timer to allow for server RAM to clear after the service has stopped
REM Use the numerical value within the ‘timeout’ command line to control how many seconds the pause will be.

TIMEOUT /t 10 /NOBREAK
ECHO.

NET START ServiceNameHere

I have a query if I need to start the multiple services and those service is taking more than 30 seconds to come up then how can i achieve that as currently its failing with error “‘net’ timed out after 30 seconds”.

Appreciate your early response. thanks

Hi. We recommend creating a batch file that uses the SC command to stop the service and check on it later.

To stop the service with SC, use:
SC STOP servicename

To check if a service was successfully stopped (after you wait for longer than 30 seconds), use the following command:
SC QUERY servicename | FIND “STATE” | FIND “STOPPED”

It will set the %ERRORLEVEL% variable to 1 if the service is not in the Stopped state.

This article may provide additional guidance.

I need a script to test users ability to start a service. Multiple users on multiple servers. Can i do that with SC or NET commands?

If you don’t mind attempting to start the service, you can also use NET START and search for errors, as shown in the example on this page.

Читайте также:  Определение неизвестного устройства windows

sir net stop telnet how to use this cmd

Make note that if the service name is two words or more you must enclose the name with quotation marks. Took me a while to find that!

I want to restart services on multiple windows servers and it take around 1 minute to be stopped . I tried to use NET STOP but its not waiting and just executed next command to start . Can someone please help me with the exact script which i can use to restart services on multiple servers.

NET STOP will only wait for about 30 seconds for the service to stop. If a service takes longer than a few seconds, NET will fail with an “Unable to wait” message.

Unfortunately there is no way to tell NET STOP to “wait longer”. And the SC utility won’t be any help as it doesn’t even attempt to wait.

We recommend using the “safeServiceStop.bat” (or “safeServiceRestart.bat”) batch file described in this article.

Save the batch file to your file system and call it from your existing batch file. Note that you should add “localhost” when calling the new batch file. For example, to stop a service called “Spooler”, use

safeServiceStop localhost Spooler

Note that the recommended solution will wait indefinitely for the service to stop. If the service never stops, your script will hang.

UPDATE 8/27/2018: We have created a free command line utility (called ServicePilot) that will wait for as long as you like when stopping the service. You can use it instead of the batch file recommended above — it’s a much simpler alternative.

Be sure to specify an appropriate value for the “-wait” flag when using ServicePilot. For example, to stop the Spooler service when it may take 5 minutes (300 seconds) to comply, use:

Note that the service will be forcibly terminated if it doesn’t stop gracefully in the given time frame.

Stopd service Tobii. It does not accept the Net Start command, and Sc start, says that the command is invalid, service name (Tobii Service)

What command are you using to stop Tobii?

Make sure you are specifying the name of the service. And enclose the name in quotes if it contains a space!

It was right, I was putting the name without (“) hence it was wrong, now it worked out . Net start” Tobii Service “

If I use net stop and and net start on a special service that have stoped working correct it doesn’t help, it still working incorrect.
But when restart the same service from services.msc it reset the service correct. What is the difference?

(service name is in one word, so not the quotes problem..)

Does NET STOP/START print any error messages to the console? Perhaps it is failing and not actually stopping/starting the service.

A common problem: NET STOP/START will fail if you are not running with sufficient rights. Make sure that you are working in an elevated prompt (started with “Run as Administrator”).

Thank you. No error messages, it just says that the servicie is stopped. And yes I run it elevated.
I will try timeout from the first comment next time i’m at the actual computer.

A really common problem when the net or SC commands and some custom services is that you have to specifiy the “Service Name” not the “Display Name” Many times they are the same but not always. Right click on the service in services.msc to see the two on the general tab and make sure you are doing “Net Start servicename” – and as said above, you still have to put it in quotes if it’s got spaces.

Читайте также:  Windows show boot options

You can change the name with sc to make it easier if you want but obviously, this might be a bad idea with system/windows services.

BTW, I know the article actually does say this but the link for “name of service” which explains this is kind of subtle and I think people might be missing that.

Thank you for pointing out the important difference between “Service Name” and “Display Name”.

Yes, we do mention the need to use the “Service Name” in the article, but maybe there is a way to make it more prominent. We’ll think about it — let us know if you have any ideas that don’t detract from the main focus of the article (using NET).

Note that our free ServicePilot utility (a more fully-featured alternative to NET.EXE) removes the name confusion by accepting both the “Service Name” and the “Display Name”. You can use either one!

Spotlight on Art. Amazy due. This got me the possibly best task ever. exactly 30 seconds after I log on, simultaneous to the desktop resolving over my SSD run system I am watching a slightly modded version of your script rock the Synergy service off then on in about 20 seconds flat. I have been, hitherto on every login for

6 months since getting Synergy having to click a taskbar icon for Synergy, then stop and start in the program, because it won’t start client clicks until the service restarts. Simply the best. Here is my modded script:
@ECHO.
@ECHO Stopping services, please wait for 10 seconds…

@ECHO OFF
REM Stop Service

NET STOP Synergy

TIMEOUT /t 10 /NOBREAK
ECHO.

NET START Synergy

forgot to thank YOU core technologies, for your recent help in getting my TASK SCHEDULER started..albeit on a completely different computer than the one mentioned above.

If the service isn’t running the START won’t happen unless you format it like this:

net stop
net start

If the service isn’t running, the first line will throw and error, but the second line will pick up and start the service for you.

I want to restart some specific service for a specific time every week.

if I used the above commands given will it work?

and if it fails to stop the service by-case will I get any email notification or is there any way to get the notification through email to me if something goes wrong?

also if the restart thorough the batch file get succeeded, will I get notified through anyway instead logging in & checking windows logs

Yes — you can use the above NET commands in conjunction with the Windows Task Scheduler to restart a specific service at a specific time. We’ll add a blog article digging into the details and let you know when it’s up.

Unfortunately there is no simple, built-in way for Windows to notify you if a service operation succeeds or fails. Some administrators of large sites have set up tools that monitor the Event Log for important events and deliver alerts, but that may be overkill if you are not in an enterprise environment.

Let us know if that solution doesn’t work for you.

I have got two batch files written within my application to stop and start a windows service.
Is there a way for me to check the status of the said service (whether it is stopped or not) and restart the same at a specific time during the day?
For more clarity –
The application service stops at, say 11pm at night and starts at 11:15pm again.
Is there a way to write time bound conditions for restarting a script excluding the duration 23:00-23:15?

Читайте также:  Ltsb windows 10 что это как узнать

Apologies if it doesnt make much sense.

Hi. You can use this simple batch file to check if a service is running or not:

Save those lines to a new .BAT file and pass the name of your service (not the display name) as the first parameter.

With regards to stopping at a specific time and restarting at another time, we recommend using the Windows Task Scheduler.

Create a basic task that stops your service at 11 PM (a batch file running NET STOP) and another that starts the service at 11:15 PM (with NET START).
The process is outlined in the “Restart multiple times per day (using the Windows Task Scheduler)” section of this related article.

Детям в интернет нельзя, он от них тупеет.

Перезапуск служб Windows из командной строки

01.06.09 13:24 / Обновлено 16.11.11 17:17 | Версия для печати Windows | Твики

Способ 1

Подойдёт службам, которые запускаются отдельным исполняемым файлом.

Запускаем services.msc и смотрим свойства интересующей службы. На вкладке «Общие» запоминаем команду запуска и имя исполняемого файла.

Имейте в виду, что в этом случае служба запустится от имени текущего пользователя.

Как вариант, можно указать автоматический перезапуск службы в случае любых сбоев — в том же окне свойств, на вкладке «Восстановление». При этом явный запуск службы не потребуется и будет произведён сразу после её остановки. С записью об ошибке в журнал.

Способ 2

Здесь имя_службы — это выводимое имя, то есть ровно то, что отображается в списке служб. Если имя на русском, например «Автоматическое обновление», то в команду тоже надо писать на русском. Имена с пробелами ограничиваются кавычками:

И будьте внимательны при написании скриптов: русскоязычные имена служб надо вводить в DOS-кодировке!

З.Ы. При чём тут «net» — непонятно, но это способ перезапуска от производителя.

Комментарии

2011.10.27 22:52:56
#cid7084

При чём тут «net» — непонятно, но это способ перезапуска от производителя.

Видимо потому, что есть возможность перезапуска службы по сети. При условии что у пользователя есть права на выполнение данного действа 😉

2011.11.16 18:04:12
#cid8116

Видимо потому, что есть возможность перезапуска службы по сети. При условии что у пользователя есть права на выполнение данного действа 😉

Вот только изначально (по сути) перезапуск службы — локальная операция. А судя по всему, даже при локальном перезапуске используется RPC.

oermolaev
2011.12.28 11:23:55
#cid11476

Приятно что первая позиция результатов поиска по моему запросу отправила на сайт который давно у меня в закладках 🙂

2011.12.28 17:10:58
#cid11507

#cid11476, oermolaev

🙂 Сам иногда охереваю.

Ищу чего-нибудь в интернете и на себя натыкаюсь.

2012.06.24 14:32:53
#cid31185

я больше охриневаю от синтаксиса cmd..

2012.06.24 20:37:12
#cid31200

я больше охриневаю от синтаксиса cmd..

Да, полная каша в синтаксисе утилит. Несмотря на то, что всё, казалось бы, написано в одной конторе.
Левая рука не знает, что делает правая.

Дмитрий
2019.01.28 10:37:14
#cid92128

Капча крутая) есть исходный код?

2019.04.25 02:08:46
#cid92164

#cid92128, Дмитрий

Капча крутая) есть исходный код?

Конечно есть. Сам писал.

ldgdemon
2019.10.11 16:27:29
#cid92250

подскажите как запустить службу с параметром «Вход в систему: с системной учётной записью»

Если вы видите эту надпись,
значит, новый движок уже в работе
и страница отображается с помощью него.

Техническая информация
Время подготовки страницы: 0.000841 c.
Кэш: частичный.

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