Пишем BAT(батник) файл для запуска и остановки службы в Windows
Возникла необходимость автоматизировать для пользователей запуск и остановку определенной службы Windows. Самое просто на первый взгляд, создание батника или Bat файла Windows. Есть и другие варианты, но решил сделать именно через батник.

Вроде все не сложно, но как всегда в Windows все не так просто, или просто, но глупо.
1. Задача:
В системе есть программа, и её Бета-версия. Запуск основной, по ярлыку. Запуск Бета-версии только после запуска службы, по окончанию, отключение этой службы. Ничего сложного нет, зайти в службы и в зависимости от задачи «включить/выключить». Но вот для некоторых сотрудников это целая проблема. Поэтому пишем батник!
2. Структура батника. После поиска структуры батника, пришел к этому варианту:
3. Меняем отражение расширений файлов. По умолчанию в Windows не отражаются расширения файлов. Правим на примере Windows 10:
— открываем любую папку;
— вверху вкладка «Вид», «Параметры», «изменить параметры папок и поиска»;
— вкладка «Вид», спускаемся до поля «Скрывать расширения для. » — снимаем галку.
Теперь файлы, в частности на рабочем столе имеют вид (на примере TXT файла):
Было «Файл», Стало «Файл.txt»
4. Создаем файл батника. Создаем «txt» файл и переименовываем его в «Запуск службы.txt». Открываем, пишем наш Bat файл:
| net start [имя службы в Windows] |
Где взять имя службы? Открываем службы, находим нужную, открываем и смотрим поле «Имя службы»:

В итоге у нас будет:
| net start AtolLicSvc(Если служба AtolLicSvc, у вас ваш вариант) |
Сохраняем и переименовываем файл с «Запуск службы.txt» в «Запуск службы.bat«
5. Проверяем работу службы. Казалось бы все! Но нет! Это же Windows! Выскакивает окно запуска службы и пропадает. А служба как спала так и спит. Что не так? Все дело в правах админа. Вроде не сложно, но пояснять сотрудникам, запускайте с правами админа, слишком сложно для их понимания! Читаем по быстрому инфу «как запустить bat файл от имени админа автоматический?», ответ:
ничего сложного.
— «правой кнопкой мыши на файле», «свойства»;
— вкладка «ярлык», . эмм. а где она? О_о
6. Вносим правки, создаем ярлык
Логично, вкладки нет, это не ярлык! Создаем из нашего батника «Запуск службы.bat» «Ярлык»: убираем батники подальше от рук пользователей, допустим на диск D. Правой кнопкой мыши на батнике: «отправить», «рабочий стол (создать ярлык)». И вот уже на ярлыке:
— «правой кнопкой мыши на ярлыке», «свойства»;
— вкладка «ярлык», кнопка «Дополнительно»;
— ставим галку «запуск от имени администратора».
7. Повторный запуск службы через BAT файл.
После этих манипуляций, если запустить ярлык «Запуск службы.bat — ярлык», служба стартует, согласно структуре в файле «net start AtolLicSvc»

Для батника который будет останавливать службу, все тоже самое. И да, вариантов решения задачи много, спорить не буду, но описал вариант решения который применил сам.
How to restart a windows service using Task Scheduler
Once the batch file is created and tested, add it to Windows Task Scheduler and run it at a specific time interval. Problem here is, when the bat file is missing or corrupt, the service won’t restart. So, are there other ways to restart a service at a specific time interval?
asked Mar 30, 2016 at 12:52
Kurt Van den Branden Kurt Van den Branden
12.3k 10 10 gold badges 77 77 silver badges 85 85 bronze badges
1 Answer 1
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler" NET START "Print Spooler"


Note: unfortunately NET RESTART does not exist.
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)?
92k 61 61 gold badges 186 186 silver badges 222 222 bronze badges
asked Sep 25, 2008 at 15:09
52.4k 32 32 gold badges 81 81 silver badges 111 111 bronze badges
18 Answers 18
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 [command] [service name] . The option 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 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
How do I restart a Windows service from a script?
it errors out because sc doesn’t wait till the service is stopped. How do I restart a service with a script?
- windows-service
- windows-command-prompt
28.6k 20 20 gold badges 98 98 silver badges 150 150 bronze badges
asked Jun 12, 2009 at 22:48
779 1 1 gold badge 9 9 silver badges 19 19 bronze badges
what about this?
Jun 12, 2009 at 22:52
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:
:stop sc stop myservice rem cause a ~10 second sleep before checking the service state ping 127.0.0.1 -n 10 -w 1000 > nul sc query myservice | find /I "STATE" | find "STOPPED" if errorlevel 1 goto :stop goto :start :start net start | find /i "My Service">nul && goto :start sc start myservice
103 2 2 bronze badges
answered Jun 12, 2009 at 22:54
8,008 1 1 gold badge 38 38 silver badges 53 53 bronze badges
Nice use of ping as a time delay.
Jun 12, 2009 at 23:34
Thanks, there’s no sleep in batch so that’s all you can do to wait 🙂
Jun 12, 2009 at 23:37
+1, and a GOTO badge. Awarded to those that use a GOTO statement with a straight face.
Jun 13, 2009 at 1:20
If only batch supported do/while loops. It’s trivial in C#, really!
Jun 13, 2009 at 1:37
In Windows Server 2008, the error level is 0 when found and 1 when not found. So I had to invert the logic and then it worked.
Jul 11, 2011 at 15:42
May be missing something, but I use this all the time:
net stop «myservice»
net start «myservice»
net stop «myservice» && net start «myservice»
answered Jun 13, 2009 at 0:23
698 4 4 silver badges 9 9 bronze badges
Dead simple with powershell:
PS >Restart-Service MySrvcHere
Even better, using display names:
PS >Restart-Service -displayname "My Service Name Here"
Get-Help Restart-Service for more
answered Jun 13, 2009 at 8:50
Factor Mystic Factor Mystic
463 1 1 gold badge 10 10 silver badges 15 15 bronze badges
If it is purely for restarting the service, you can use
Net stop myservice Net start myservice
However, if you want access to the options of sc, you can use the start /wait command
start /B /WAIT CMD /C "sc stop myservice" start /B /WAIT CMD /C "sc start myservice"
this technique is a more general solution that can be applied to any command.
answered Jun 13, 2009 at 9:29
Peter Stuer Peter Stuer
1,473 9 9 silver badges 11 11 bronze badges
sc stop myservice will just send the stop command and return before the service is stopped. Calling sc with start /b won’t help.
Jul 30, 2018 at 9:30
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.
net stop Server /y net start Server
It would be helpful for automatic script execution.
answered May 20, 2011 at 14:55
Fedir RYKHTIK Fedir RYKHTIK
597 1 1 gold badge 9 9 silver badges 18 18 bronze badges
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»
In vbscipt it’s a little more code to stop a service and its’ dependants:
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "!\\" & strComputer & "\root\cimv2") Set colServiceList = objWMIService.ExecQuery("Associators of " _ & " Where " _ & "AssocClass=Win32_DependentService " & "Role=Antecedent" ) For each objService in colServiceList objService.StopService() Next Wscript.Sleep 20000 Set colServiceList = objWMIService.ExecQuery _ ("Select * from Win32_Service where Name='myservice'") For each objService in colServiceList errReturn = objService.StopService() Next
Here’s starting a service and anything it depends on (this should be familiar)
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "!\\" & strComputer & "\root\cimv2") Set colServiceList = objWMIService.ExecQuery _ ("Select * from Win32_Service where Name='Myservice'") For each objService in colServiceList errReturn = objService.StartService() Next Wscript.Sleep 20000 Set colServiceList = objWMIService.ExecQuery("Associators of " _ & " Where " _ & "AssocClass=Win32_DependentService " & "Role=Dependent" ) For each objService in colServiceList objService.StartService() Next