- Copy and save the below script as MaintainService.ps1
- Open Powershell and navigate to the path where the script is saved
- Simply type part of the script name and then press tab for auto-complete
- You have to provide a service name and action (stop, start, restart) as part of the script parameters.
<# Author: Khoa Nguyen PS C:\Users\KoA\Dropbox\Code-Store\powershell> $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 5 1 15063 608 This is a quick script to start, stop and restart a service. The script will validate that the service exists and the required action parameter (stop, start, restart) is valid prior to executing the script. Sample Executions: PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Start Spooler is stopped, preparing to start... Spooler - Running PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Stop Spooler is running, preparing to stop... Spooler - Stopped PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 FakeService Start FakeService not found PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 FakeService Stop FakeService not found PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Start Spooler is stopped, preparing to start... Spooler - Running PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Restart Spooler is running, preparing to restart... Spooler - Running PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Stop Spooler is running, preparing to stop... Spooler - Stopped PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Restart Spooler is stopped, preparing to start... Spooler - Running PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 Spooler Check Action parameter is missing or invalid! PS C:\Users\KoA\Dropbox\Code-Store\powershell> .\MaintainService.ps1 FakeService Check FakeService not found PS C:\Users\KoA\Dropbox\Code-Store\powershell> #> param ( [Parameter(Mandatory=$true)] [string] $ServiceName, [string] $Action ) #Checks if ServiceName exists and provides ServiceStatus function CheckMyService ($ServiceName) { if (Get-Service $ServiceName -ErrorAction SilentlyContinue) { $ServiceStatus = (Get-Service -Name $ServiceName).Status Write-Host $ServiceName "-" $ServiceStatus } else { Write-Host "$ServiceName not found" } } #Checks if service exists if (Get-Service $ServiceName -ErrorAction SilentlyContinue) { #Condition if user wants to stop a service if ($Action -eq 'Stop') { if ((Get-Service -Name $ServiceName).Status -eq 'Running') { Write-Host $ServiceName "is running, preparing to stop..." Get-Service -Name $ServiceName | Stop-Service -ErrorAction SilentlyContinue CheckMyService $ServiceName } elseif ((Get-Service -Name $ServiceName).Status -eq 'Stopped') { Write-Host $ServiceName "already stopped!" } else { Write-Host $ServiceName "-" $ServiceStatus } } #Condition if user wants to start a service elseif ($Action -eq 'Start') { if ((Get-Service -Name $ServiceName).Status -eq 'Running') { Write-Host $ServiceName "already running!" } elseif ((Get-Service -Name $ServiceName).Status -eq 'Stopped') { Write-Host $ServiceName "is stopped, preparing to start..." Get-Service -Name $ServiceName | Start-Service -ErrorAction SilentlyContinue CheckMyService $ServiceName } else { Write-Host $ServiceName "-" $ServiceStatus } } #Condition if user wants to restart a service elseif ($Action -eq 'Restart') { if ((Get-Service -Name $ServiceName).Status -eq 'Running') { Write-Host $ServiceName "is running, preparing to restart..." Get-Service -Name $ServiceName | Stop-Service -ErrorAction SilentlyContinue Get-Service -Name $ServiceName | Start-Service -ErrorAction SilentlyContinue CheckMyService $ServiceName } elseif ((Get-Service -Name $ServiceName).Status -eq 'Stopped') { Write-Host $ServiceName "is stopped, preparing to start..." Get-Service -Name $ServiceName | Start-Service -ErrorAction SilentlyContinue CheckMyService $ServiceName } } #Condition if action is anything other than stop, start, restart else { Write-Host "Action parameter is missing or invalid!" } } #Condition if provided ServiceName is invalid else { Write-Host "$ServiceName not found" }
cmd, Скрипт перезапуска службы
Скрипт останавливает службу «service-name».
Убивает процесс «service-name.exe», если такой есть.
Запускает службу обратно в работу.
В промежутках между командами задана пауза, чтобы дать службе/процессу время на завершение.
.bat-скрипт
REM CODEPAGE Win 866 (OEM)
REM Останавливаем службу
NET stop service-name
REM Ждём
TIMEOUT /T 120 /NOBREAK
REM Проверяем наличие процесса службы (просто для информации)
TASKLIST /FI «IMAGENAME eq service-name.exe»
REM Убиваем службу. На случай, если она зависла и не останавливается
TASKKILL /F /IM service-name.exe
REM Ждём
TIMEOUT /T 120 /NOBREAK
REM Запускаем службу обратно в работу
NET start service-name
#скрипты #windows #cmd
2019-08-20 22:04:53
I want to restart some specific service for a specific time every week. Can I use the NET command?
— Shanmuga
Hi Shanmuga.
Yes. With the help of the Windows Task Scheduler, you can use the NET command to restart a specific service at a specific time.
To do so:
1. Find the name of your service
Each Windows Service has two names — a short service name and a friendly display name. We need the service name for the NET command.
If you don’t already know the service name, or want to validate it:
-
Launch the Windows Services application. You can find it by searching for “services” in the Control Panel, or by running services.msc at a command prompt.
- Scroll to locate your service in the list:
-
Double-click the entry to open the service’s properties. The service name is displayed at the top.
Here we see that the name of the Print Spooler service is actually “Spooler”:
2. Create a batch file to restart your service
With the service name in hand, we can now use the NET command to restart the service.
Create a new batch file and enter the following two commands:
NET STOP «Your Service Name«
NET START «Your Service Name«
Please replace Your Service Name with the service name identified in step 1. The quotes are required if the service name contains a space.
For example, if your service name is “Spooler”, the batch file should look like this:
NET STOP «Spooler»
NET START «Spooler»
Save the batch file to a well-known location. We’ll use it in the next step.
Test the batch file
At this point, we recommend performing a quick test to ensure that the batch file works as expected. Run it from an administrative command prompt and confirm that it restarts your service.
3. Create a scheduled task to run the batch file at the time you wish to restart the service
Now that you are able to restart the service with the batch file, let’s schedule it to run whenever you like.
For example, here is how we would restart the Print Spooler service every Sunday at 1 AM:
-
Open the Windows Task Scheduler. You start it from the Control Panel or by running taskschd.msc from a command prompt.
-
Click Create Basic Task on the right:
The Create Basic Task Wizard window will come up.
-
Give the task a descriptive name:
Click Next to continue.
-
Select Weekly and click Next:
-
Set the day and time to restart the service:
Click Next to continue.
-
Ensure that the action is Start a program and move to the next step:
-
Enter the full path to the batch file you created to restart the service:
Click Next to continue.
-
Review the summary and make sure that everything looks good.
Check the Open the Properties dialog… box at the bottom because we’ll need to adjust one of the tasks properties:
Click Finish.
-
And finally, in the Properties window, check the Run with highest privileges box. The batch file must run with administrative rights so that it can restart the service.
Click OK to save your settings.
Going forward, the new task will come alive at the scheduled time to promptly restart the service. You should be good to go.
Improvement: Use ServicePilot instead of NET for better reliability
While NET.EXE will work for most situations, there are a few scenarios where it may fall short.
Does your service:
- take longer than 30 seconds to shut down?
- occasionally hang and refuse to stop?
If so, the NET STOP command may fail. And when that happens, the subsequent call to NET START will fail too (because the service will not be idle). The end result is that your service will be left in an unusable/unresponsive state!
Our free ServicePilot utility was built to work around NET’s shortcomings. It will wait for longer than 30 seconds if necessary and will do its best to forcibly terminate an unresponsive service.
To use ServicePilot instead of NET:
-
Download ServicePilot from our website. Save the executable in a well-known location (e.g. C:\Apps\ServicePilot\ServicePilot.exe).
-
Edit the batch file you created to restart the service.
-
Delete the two NET lines.
-
Add the following line (adjusting the full path to ServicePilot and your service name as necessary):
C:\Apps\ServicePilot\ServicePilot.exe -restart -wait 300 «Your Service Name«
Note: The -wait 300 parameter instructs ServicePilot to wait up to 300 seconds (5 minutes) for the service to stop and restart. Feel free to increase (or decrease) the timeout based your specific use case.
-
Save the batch file.
As you did with the NET version, please perform a quick test to ensure that the updated batch file works as expected. Launch it from an administrative command prompt and confirm that it restarts your service.
Best of luck with your service!
UPDATE: Use our free Service Scheduler utility instead of the Task Scheduler
We got tired of manually creating batch files and scheduled tasks to control our services so we created a free application to do it all. 🙂
With Service Scheduler, you can easily start, stop or restart any Windows Service — daily, weekly or monthly at a time of your choosing:
Service Scheduler is completely free and super easy to use. You can schedule your service in seconds:
Download Service Scheduler and check it out today!
You may also like…
Задача:
Необходимо перезапустить из командного (bat) файла какую-либо службу Windows, причем необходимо убедиться, что указанная служба действительно запустилась.
Решение:
Приведу два примера. Они по-сути одинаковые, только проверка состояния службы Windows немного отличается.
-
Вариант 1:
Код: Выделить всё
@Echo Off Net Stop Spooler PING -n 1 -w 10000 192.168.253.253 > nul :ReStartService Net Start Spooler net start | find /i "Диспетчер очереди печати">NUL if %errorlevel%==1 echo GoTo ReStartService EXIT
-
Вариант 2:
Код: Выделить всё
@Echo Off Net Stop Spooler PING -n 1 -w 10000 192.168.253.253 > nul :ReStartService Net Start Spooler SC query Spooler | find /i "1 STOPPED" > nul if %errorlevel%==0 echo GoTo ReStartService EXIT
В обоих вариантах алгоритм такой:
-
Завершаем службу
-
Делаем паузу 10 секунд командой PING до несуществующего хоста
-
Запускаем службу
-
Выполняем проверку
-
Если служба не запущена, возвращаемся к метке «ReStartService», иначе — завершаем работу командного файла
Различие методов — в способе проверки состояния службы. В первом методе мы просматриваем весь список запущенных служб на предмет наличия в нем псевдонима нашей службы (например, у службы «Spooler» псевдоним в русскоязычной локализации Windows будет «Диспетчер очереди печати»).
Во втором методе мы ищем в тексте, выдаваемом командой «SC query» строку «1 STOPPED», которая показывает состояние службы и в данном случае означает, что служба остановлена. Более того, строка «1 STOPPED» во всех локализациях отображается одинаково, поэтому второй метод является более универсальным.
I wrote some batch files today for restarting services on windows. The bat files can be used to restart ColdFusion MX or IIS services on Windows NT/2000/XP.
Batch File to restart ColdFusion MX
@echo off REM - File: cfmxrestart.bat REM - Description: Restart's ColdFusion MX Services REM - Author: Pete Freitag echo Restarting ColdFusion MX... echo ====================================================== net stop "ColdFusion MX Application Server" net stop "ColdFusion MX ODBC Agent" net stop "ColdFusion MX ODBC Server" net start "ColdFusion MX Application Server" net start "ColdFusion MX ODBC Agent" net start "ColdFusion MX ODBC Server" echo ====================================================== echo ColdFusion MX Restarted
Batch file to restart IIS
@echo off REM - File: iisrestart.bat REM - Description: Restart's IIS (Web, FTP, SMTP) REM - Author: Pete Freitag REM - ADD REM comments if you don't want to restart any REM - of Services echo Restarting IIS... echo ====================================================== net stop "World Wide Web Publishing Service" net start "World Wide Web Publishing Service" net stop "FTP Publishing Service" net start "FTP Publishing Service" net stop "Simple Mail Transport Protocol (SMTP)" net start "Simple Mail Transport Protocol (SMTP)" echo ====================================================== echo IIS Restarted
Bat files are handy because you can restart multiple services with one command. You can either double click the bat file to run it, schedule it, or throw it in c:\windows\system32 and then run it from anywhere in the command prompt or (Start->Run)
Batch Files to Restart Services on Windows was first published on October 09, 2002.