- Start or stop Windows service from command line (CMD)
- How to: Install and uninstall Windows services
- Install using InstallUtil.exe utility
- Uninstall using InstallUtil.exe utility
- Install using PowerShell
- Uninstall using PowerShell
- How to: Start Services
- Specify how a service should start
- Start a service from Server Explorer
- Start a service from Services
- Start a service from code
- Практическое руководство. Запуск служб How to: Start Services
- Настройка способа запуска службы To specify how a service should start
- Запуск службы вручную из обозревателя сервера To manually start a service from Server Explorer
- Запуск службы вручную из диспетчера служб To manually start a service from Services Control Manager
- Запуск службы вручную из кода To manually start a service from code
Start or stop Windows service from command line (CMD)
We normally use Services.msc to start or stop or disable or enable any service. We can do the same from windows command line also using net and sc utilities. Below are commands for controlling the operation of a service.
Command to stop a service:
To start a service:
You need to have administrator privileges to run net start/stop commands. If you are just a normal user on the computer, you would get an error like below.
To disable a service:
To enable a service:
To make a service start automatically with system boot:
Note: Space is mandatory after ‘=’ in the above sc commands.
This SC command works on a Windows 7 machine and also on the down-level editions of Windows i.e Windows XP/2003 and Windows Vista. Again, if you do not have administrator previliges you would get the below error.
Note that the service name is not the display name of a service. Each service is given a unique identification name which can be used with net or sc commands. For example, Remote procedure call (RPC) is the display name of the service. But the service name we need to use in the above commands is RpcSs.
So to start Remote procedure call service the command is:
These service names are listed below for each service. The first column shows the display name of a service and the second column shows the service name that should be used in net start or net stop or sc config commands.
How to: Install and uninstall Windows services
If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. For more information, see Create an installer package (Windows desktop).
If you want to uninstall a service from your computer, don’t follow the steps in this article. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
To use the steps in this article, you first need to add a service installer to your Windows service. For more information, see Walkthrough: Creating a Windows service app.
You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Before you can run the project, you must install the service in the project.
You can use Server Explorer to verify that you’ve installed or uninstalled your service.
Install using InstallUtil.exe utility
From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
The Developer Command Prompt for Visual Studio appears.
Access the directory where your project’s compiled executable file is located.
Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
- For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
- For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Uninstall using InstallUtil.exe utility
From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
The Developer Command Prompt for Visual Studio appears.
Run InstallUtil.exe from the command prompt with your project’s output as a parameter:
After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Install using PowerShell
From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Access the directory where your project’s compiled executable file is located.
Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Uninstall using PowerShell
From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Run the Remove-Service cmdlet with the name of your service as parameter:
After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
How to: Start Services
After a service is installed, it must be started. Starting calls the OnStart method on the service class. Usually, the OnStart method defines the useful work the service will perform. After a service starts, it remains active until it is manually paused or stopped.
Services can be set up to start automatically or manually. A service that starts automatically will be started when the computer on which it is installed is rebooted or first turned on. A user must start a service that starts manually.
By default, services created with Visual Studio are set to start manually.
There are several ways you can manually start a service — from Server Explorer, from the Services Control Manager, or from code using a component called the ServiceController.
You set the StartType property on the ServiceInstaller class to determine whether a service should be started manually or automatically.
Specify how a service should start
After creating your service, add the necessary installers for it. For more information, see How to: Add Installers to Your Service Application.
In the designer, click the service installer for the service you are working with.
In the Properties window, set the StartType property to one of the following:
To have your service install | Set this value |
---|---|
When the computer is restarted | Automatic |
When an explicit user action starts the service | Manual |
To prevent your service from being started at all, you can set the StartType property to Disabled. You might do this if you are going to reboot a server several times and want to save time by preventing the services that would normally start from starting up.
These and other properties can be changed after your service is installed.
There are several ways you can start a service that has its StartType process set to Manual — from Server Explorer, from the Windows Services Control Manager, or from code. It is important to note that not all of these methods actually start the service in the context of the Services Control Manager; Server Explorer and programmatic methods of starting the service actually manipulate the controller.
Start a service from Server Explorer
In Server Explorer, add the server you want if it is not already listed. For more information, see How to: Access and Initialize Server Explorer-Database Explorer.
Expand the Services node, and then locate the service you want to start.
Right-click the name of the service, and then select Start.
Start a service from Services
Open the Services app.
Select your service in the list, right-click it, and then select Start.
Start a service from code
Create an instance of the ServiceController class, and configure it to interact with the service you want to administer.
Call the Start method to start the service.
Практическое руководство. Запуск служб How to: Start Services
Установленную службу необходимо запустить. After a service is installed, it must be started. Процедура запуска вызывает метод OnStart в классе службы. Starting calls the OnStart method on the service class. Как правило, метод OnStart определяет полезные действия, которые будет выполнять служба. Usually, the OnStart method defines the useful work the service will perform. Запущенная служба остается активной, пока не будет приостановлена или остановлена вручную. After a service starts, it remains active until it is manually paused or stopped.
Службы можно настроить на запуск автоматически или вручную. Services can be set up to start automatically or manually. Служба, которая запускается автоматически, будет запущена при первом включении или перезагрузке компьютера, на котором она установлена. A service that starts automatically will be started when the computer on which it is installed is rebooted or first turned on. Службу, которая запускается вручную, должен запустить пользователь. A user must start a service that starts manually.
По умолчанию службы, созданные с помощью Visual Studio, настроены на запуск вручную. By default, services created with Visual Studio are set to start manually.
Есть несколько способов запуска службы вручную: из диспетчера служб или обозревателя сервера либо из кода, используя компонент, который называется ServiceController. There are several ways you can manually start a service — from Server Explorer, from the Services Control Manager, or from code using a component called the ServiceController.
Вы можете задать свойство StartType в классе ServiceInstaller, чтобы определить способ запуска службы — вручную или автоматически. You set the StartType property on the ServiceInstaller class to determine whether a service should be started manually or automatically.
Настройка способа запуска службы To specify how a service should start
Создав службу, добавьте для нее необходимые установщики. After creating your service, add the necessary installers for it. Дополнительные сведения см. в разделе Практическое руководство. Добавление установщиков в приложение-службу. For more information, see How to: Add Installers to Your Service Application.
В конструкторе щелкните установщик процессов службы, с которой вы работаете. In the designer, click the service installer for the service you are working with.
В окне свойств задайте свойству StartType одно из следующих значений: In the Properties window, set the StartType property to one of the following:
Чтобы установить службу To have your service install | Задайте это значение Set this value |
---|---|
При перезапуске компьютера When the computer is restarted | Автоматический Automatic |
При запуске службы с помощью явного действия пользователя When an explicit user action starts the service | Manual (Вручную) Manual |
Чтобы полностью запретить запуск службы, можно задать свойству StartType значение Disabled (Отключено). To prevent your service from being started at all, you can set the StartType property to Disabled. Это можно сделать, если вы собираетесь перезагружать сервер несколько раз и хотите сэкономить время, запретив запуск служб, которые обычно запускаются одновременно. You might do this if you are going to reboot a server several times and want to save time by preventing the services that would normally start from starting up.
Эти и другие свойства можно изменить после установки службы. These and other properties can be changed after your service is installed.
Есть несколько способов запуска службы, для процесса StartType которой настроено значение Manual (Вручную): из диспетчера служб или обозревателя серверов либо из кода. There are several ways you can start a service that has its StartType process set to Manual — from Server Explorer, from the Windows Services Control Manager, or from code. Важно отметить, что в действительности не все эти методы приводят к запуску службы в контексте диспетчера служб. При использовании обозревателя сервера и программных способов применяется контроллер. It is important to note that not all of these methods actually start the service in the context of the Services Control Manager; Server Explorer and programmatic methods of starting the service actually manipulate the controller.
Запуск службы вручную из обозревателя сервера To manually start a service from Server Explorer
В обозревателе сервера добавьте нужный сервер, если его нет в списке. In Server Explorer, add the server you want if it is not already listed. Дополнительные сведения см. в разделах «Практическое руководство. Подключение и инициализация обозревателя серверов или обозревателя баз данных». For more information, see How to: Access and Initialize Server Explorer-Database Explorer.
Разверните узел Службы и выберите службу, которую нужно запустить. Expand the Services node, and then locate the service you want to start.
Щелкните службу правой кнопкой мыши и выберите команду Запустить. Right-click the name of the service, and click Start.
Запуск службы вручную из диспетчера служб To manually start a service from Services Control Manager
Откройте диспетчер служб, сделав следующее: Open the Services Control Manager by doing one of the following:
В Windows XP и 2000 Professional щелкните правой кнопкой мыши значок Мой компьютер на рабочем столе и выберите Управление. In Windows XP and 2000 Professional, right-click My Computer on the desktop, and then click Manage. В открывшемся диалоговом окне разверните узел Службы и приложения. In the dialog box that appears, expand the Services and Applications node.
В Windows Server 2003 и Windows 2000 Server нажмите кнопку Пуск, выберите Программы, Администрирование и Службы. In Windows Server 2003 and Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
В Windows NT версии 4.0 можно открыть это диалоговое окно на панели управления. In Windows NT version 4.0, you can open this dialog box from Control Panel.
Теперь ваша служба должна отобразиться в списке Службы. You should now see your service listed in the Services section of the window.
Выберите службу в списке, щелкните ее правой кнопкой мыши и нажмите кнопку Запустить. Select your service in the list, right-click it, and then click Start.
Запуск службы вручную из кода To manually start a service from code
Создайте экземпляр класса ServiceController и настройте его для взаимодействия со службой, которой нужно управлять. Create an instance of the ServiceController class, and configure it to interact with the service you want to administer.
Чтобы запустить службу, вызовите метод Start. Call the Start method to start the service.