sc.exe удалить sc.exe delete
Удаляет подраздел службы из реестра. Deletes a service subkey from the registry. Если служба запущена или другой процесс имеет открытый обработчик, служба помечается для удаления. If the service is running or if another process has an open handle to the service, the service is marked for deletion.
Мы не рекомендуем использовать эту команду для удаления встроенных служб операционной системы, таких как DHCP, DNS или службы IIS. We don’t recommend you to use this command to delete built-in operating system services such as DHCP, DNS, or Internet Information Services. Сведения об установке, удалении и перенастройке ролей операционной системы, служб и компонентов см. в разделе Установка и удаление ролей, служб ролей или компонентов . To install, remove, or reconfigure operating system roles, services and components, see Install or Uninstall Roles, Role Services, or Features
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
Указывает имя удаленного сервера, на котором расположена служба. Specifies the name of the remote server on which the service is located. Имя должно использовать формат UNC (например, \ MyServer). The name must use the Universal Naming Convention (UNC) format (for example, \myserver). Чтобы запустить SC.exe локально, не используйте этот параметр. To run SC.exe locally, don’t use this parameter. | |
Указывает имя службы, возвращенное операцией жеткэйнаме . Specifies the service name returned by the getkeyname operation. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Примеры Examples
Чтобы удалить подраздел Service невсерв из реестра на локальном компьютере, введите: To delete the service subkey NewServ from the registry on the local computer, type:
Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
Если вы разрабатываете службу Windows с помощью .NET Framework, вы можете быстро установить приложение службы с помощью служебной программы командной строки InstallUtil.exe или PowerShell. 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. Если вы являетесь разработчиком и хотите создать службу Windows, которую пользователи могут устанавливать и удалять, можно использовать набор инструментов WiX или коммерческие средства, такие как Advanced Installer, InstallShield или другие. 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. См. сведения о создании пакета установщика (классическое приложение Windows). 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. Следует отметить, что многие службы являются составной частью ОС Windows. Если их удалить, это может привести к нестабильной работе системы. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
Чтобы использовать процедуру, описанную в этой статье, сначала необходимо добавить установщик службы в свою службу Windows. To use the steps in this article, you first need to add a service installer to your Windows service. Дополнительные сведения см. в разделе Пошаговое руководство: создание диспетчера служб Windows. For more information, see Walkthrough: Creating a Windows service app.
Проекты служб Windows нельзя запускать непосредственно из среды разработки Visual Studio путем нажатия клавиши F5. 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. Дополнительные сведения см. в разделе Практическое руководство. Использование обозревателя сервера в Visual Studio. For more information, see How to use Server Explorer in Visual Studio.
Установка службы вручную с помощью служебной программы InstallUtil.exe Install your service manually using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Запустите InstallUtil.exe из командной строки, указав исполняемый файл проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
Если вы используете командную строку разработчика для Visual Studio, системный путь должен указывать на файл InstallUtil.exe. 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. Этот инструмент устанавливается вместе с платформой .NET Framework в папку %WINDIR%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
Пример: For example:
- Для 32-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: если каталог установки Windows — C:\Windows, по умолчанию используется путь C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe. 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.
- Для 64-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: по умолчанию используется путь C:\Windows\Microsoft.NET\Framework64\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.
Удаление службы вручную с помощью служебной программы InstallUtil.exe Uninstall your service manually using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Запустите InstallUtil.exe из командной строки, указав выходные данные проекта в качестве параметра: 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. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Установка службы вручную с помощью PowerShell Install your service manually using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows 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.
Выполните командлет New-Service, указав в качестве параметров выходные данные проекта и имя службы. Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Удаление службы вручную с помощью PowerShell Uninstall your service manually using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Выполните командлет Remove-Service, указав в качестве параметра имя службы. 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. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Delete method of the Win32_Service class
The Delete WMI class method deletes an existing service.
This topic uses Managed Object Format (MOF) syntax. For more information about using this method, see Calling a Method.
Syntax
Parameters
This method has no parameters.
Return value
Returns one of the values listed in the following list or any other value to indicate an error. For additional error codes, see WMI Error Constants or WbemErrorEnum. For general HRESULT values, see System Error Codes.
The request was accepted.
The request is not supported.
The user did not have the necessary access.
The service cannot be stopped because other services that are running are dependent on it.
The requested control code is not valid, or it is unacceptable to the service.
The requested control code cannot be sent to the service because the state of the service (Win32_BaseService.State property) is equal to 0, 1, or 2.
The service has not been started.
The service did not respond to the start request in a timely fashion.
Unknown failure when starting the service.
The directory path to the service executable file was not found.
The service is already running.
The database to add a new service is locked.
A dependency this service relies on has been removed from the system.
The service failed to find the service needed from a dependent service.
The service has been disabled from the system.
The service does not have the correct authentication to run on the system.
This service is being removed from the system.
The service has no execution thread.
The service has circular dependencies when it starts.
A service is running under the same name.
The service name has invalid characters.
Invalid parameters have been passed to the service.
The account under which this service runs is either invalid or lacks the permissions to run the service.
The service exists in the database of services available from the system.
The service is currently paused in the system.
Remarks
As your organization changes, you might decide to remove certain services from certain computers. In-house and third-party services can be removed by using WMI, while operating system services can be removed by using Sysocmgr.exe.
When preparing to remove services, keep the following information in mind:
Services must be stopped before you remove them. If the service is running when you issue the delete command, the service is marked for deletion, but it continues to run until it stops and all open handles are closed.
If the service is never stopped, that service will never be deleted.
Removing a service does not remove the service’s executable file.
Removing a service by using WMI deletes the related registry entries under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. As a result, the service is no longer installed and is not available through the Services snap-in. However, WMI does not delete the executable file, meaning you could easily reinstall the service. To delete the executable file, you must retrieve the path name and then delete the file.
Removing a base Windows 2000 service (for example, DHCP) by using WMI deletes the registry entries for that service but does not remove the shortcut from the Administrative Tools menu or remove the service from the Windows Components Wizard. This can confuse anyone trying to determine how the computer has been configured.
For example, if you remove the DHCP service by using a WMI script, the DHCP service is no longer listed in the Services snap-in. However, a nonfunctioning shortcut to the DHCP console remains in the Administrative Tools menu, and if you start the Windows Component Wizard, it indicates that the DHCP service is installed.
Because of this, you should always use Sysocmgr.exe to programmatically remove Windows 2000 services.
Examples
The following VBScript code sample describes how to delete a service.
The following Perl code sample describes how to delete a service.