В процессе использования Windows 11 или Windows 10 в системе неизбежно накапливается большое количество служб. Обычно они появляются при установке программ и постоянно висят в памяти расходуя ресурсы компьютера.
Обычно такие ненужные службы просто останавливают и переводят в ручной режим запуска. Но, если вы уверены, что какая-то из служб вам точно не понадобится, то вы можете полностью удалить ее из системы. В этой статье мы рассмотрим, сразу три способа, как удалить службу в Windows 11 и Windows 10. Это будут способы с использованием редактора реестра, командной строки и PowerShell.
Удаление через командную строку
Первый способ удаления служб из операционной системы Windows 11 и Windows 10 заключается в использовании командной строки и команды «sc delete». Данная команда выполняет удаление раздела реестра, который отвечает за работу указанной службы, что приводит к удалению службы из системы. Если в момент удаления служба все еще работает, то она помечается для удаления в будущем.
Для того чтобы удалить службу при помощи данной команды необходимо знать ее имя, под которым она зарегистрирована в системе. Чтобы узнать это имя можно воспользоваться встроенной программой «Службы». Чтобы запустить данную программу нажмите комбинацию клавиш Win-R и выполните команду «services.msc».
В открывшемся окне нужно найти службу, которую вы хотите удалить из Windows 11 или Windows 10, кликнуть по ней правой кнопкой мышки и перейти в «Свойства».
В результате появится небольшое окно с информацией. Здесь, на вкладке «Общее», в самом верху окна будет указано «Имя службы». То именно то имя, которое нам и нужно для удаления.
После этого нужно открыть командную строку с правами администратора. Для этого проще всего воспользоваться поиском в меню «Пуск». Откройте меню «Пуск», введите команду «cmd» и запустите ее от имени админа.
После запуска командной строки можно приступать к удалению службы. Для этого сначала желательно остановить работу службы при помощи команды:
sc stop ServiceName
Где «ServiceName» — это название службы, которое вы узнали на предыдущем этапе.
После остановки можно выполнять команду для удаления:
sc delete ServiceName
Как и в предыдущем случае, «ServiceName» нужно заменить на название нужной вам службы.
После этого в командной строке должно появиться сообщение об успешном удалении. Но, если что-то не сработало, то вы можете попробовать другой способ.
Удаление через PowerShell
Также для удаления службы в Windows 11 и Windows 10 вы можете воспользоваться PowerShell. Как и обычную командную строку, консоль PowerShell нужно запускать с правами администратора. Для этого откройте меню «Пуск», введите поисковый запрос «PowerShell» и запустите его от имени админа.
Работу в PowerShell можно начать с выполнения команды (командлета) «Get-Service», который выведет на экран список всех зарегистрированных в системе служб с указанием их имен. Но, если имя слишком длинное, то оно не поместится на экране. В этом случае вы можете узнать его через «services.msc», так как это описано в начале статьи.
После этого удаляемую службу желательно остановить. Для этого выполняем команду:
Stop-Service -Name ServiceName -Force
Где «ServiceName» — это название, которое вы узнали на предыдущем этапе.
Завершающий этап – удаление службы из Windows 11 или Windows 10. Для этого выполняем команду:
Remove-Service -Name ServiceName
Как и в предыдущем случае, «ServiceName» нужно заменить на название нужной вам службы.
Больше информации об управлении службами при помощи PowerShell можно узнать на сайте Майкрософт:
- Get-Service;
- Stop-Service;
- Remove-Service.
Удаление через Редактор реестра
Если описанные выше способы не сработали (что маловероятно), то вы можете попробовать удалить службу через редактор реестра Windows. Для этого нажмите комбинацию клавиш Win-R и в открывшемся меню выполните команду «regedit».
Таким образом вы откроете редактор реестра Windows 10. Здесь нужно перейти в раздел:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
И найти подраздел с названием службы, которую необходимо удалить из системы.
Для удаления службы необходимо удалить весь подраздел с нужным названием и перезагрузить компьютер.
Автор
Александр Степушин
Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.
Остались вопросы?
Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.
- Deleting a Service Using the Command Line in PowerShell
- Deleting a Service Using PowerShell
There will be multiple situations where we need to clean the services up. This problem was caused by uninstalling software leaving its driver entries or service in the registry.
Windows will try to load them at every boot, fails, and log the error to the System Event log at every startup.
This article tells us how to delete an orphaned service in Windows 10 and earlier using the command-line and PowerShell.
Deleting a Service Using the Command Line in PowerShell
The sc.exe
legacy command-line tool in Windows can create, read, edit, or delete Windows Services. To remove services in Windows, use the following command-line syntax from admin Command Prompt.
Please ensure that you run in an elevated command prompt with administrator privileges.
The value service_name
refers to the short name of the service instead of its display name. Open the Services MMC and double-click the service you want to check to find the short name.
Deleting a Service Using PowerShell
You can also run the sc.exe command in PowerShell.
We need to specify the extension sc.exe
when running it in PowerShell because the command SC
in PowerShell will be interpreted as Set-Content
, a built-in cmdlet in PowerShell.
sc.exe delete service_name
To get the name of the service to be removed, run Get-Service
on the machine known to have the orphaned service. We will use the column marked Name
for the service name in the PowerShell script.
We can use the following native commands from the PowerShell administrator window to delete a service.
$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()
It’s even easier if we have PowerShell 6.0 installed. In PowerShell 6 and higher, you can use this syntax to remove a service:
Remove-Service -Name ServiceName
Running the Remove-Service
command in older versions of PowerShell below 6.0 shows the error:
The Remove-Service
cmdlet is not recognized as the name of a cmdlet, function, script file, or operable program.
В Windows вы можете управлять службами не только из графической консоли services.msc или утилиты командной строки Sc.exe (первоначальна включалась в пакет ресурсов Resource Kit), но и с помощью PowerShell. В этой статье мы смотрим различные сценарии управления службами Windows с помощью PowerShell.
Содержание:
- Основные командлеты PowerShell для управления службами Windows
- Остановка, запуск, приостановка и перезапуск служб из PowerShell
- Set-Service – изменение настроек службы Windows
- Создание и удаление служб Windows c помощью PowerShell
- Изменение учетной записи для запуска службы
Основные командлеты PowerShell для управления службами Windows
Существует восемь основных командлетов Service, предназначенных для просмотра состояния и управления службами Windows.
Чтобы получить весь список командлетов Service, введите команду:
Get-Help \*-Service
- Get-Service — позволяет получить службы на локальном или удаленном компьютере, как запущенные, так и остановленные;
- New-Service – создать службу. Создает в реестре и базе данных служб новую запись для службы Windows;
- Restart-Service – перезапустить службу. Передает сообщение об перезапуске службы через Windows Service Controller
- Resume-Service – возобновить службы. Отсылает сообщение о возобновлении работы диспетчеру служб Windows;
- Set-Service — изменить параметры локальной или удаленной службы, включая состояние, описание, отображаемое имя и режим запуска. Этот командлет также можно использовать для запуска, остановки или приостановки службы;
- Start-Service – запустить службу;
- Stop-Service – остановить службу (отсылает сообщение об остановке диспетчеру служб Windows);
- Suspend-Service приостановить службу. Приостановленная служба по-прежнему выполняется, однако ее работа прекращается до возобновления работы службы, например с помощью командлета Resume-Service.
Получить подробное описание и примеры использования конкретного командлета можно через Get-help:
Get-Help Start-Service
Get-Service: получаем список служб и их состояние
Получить список и состояние (Running/Stopped) службы на локальном или удаленном компьютере можно с помощью командлета Get-Service. Параметр -Name позволяет делать отбор по имени службы. Имя службы можно задать с использованием подстановочного символа *.
Если вы не знаете точное имя службы, есть возможность найти службы по отображаемому имени с помощью параметра –DisplayName. Можно использовать список значений и подстановочные знаки.
.
Командлет Get-Service можно использовать для получения состояния служб на удаленных компьютерах, указав параметр -ComputerName. Можно опросить статус службы сразу на множестве удаленных компьютеров, их имена нужно перечислить через запятую. Например, приведенная ниже команда получает состояние службы Spooler на удаленных компьютерах RM1 и RM2.
Get-Service spooler –ComputerName RM1,RM2
Status Name DisplayName ------ ---- ----------- Running spooler Print Spooler Stopped spooler Print Spooler
Вывести все свойства службы позволит командлет Select-Object:
Get-Service spooler | Select-Object *
Командлет Select-Object позволит вывести определенные свойства службы. Например, нам нужно вывести имя, статус и доступные возможности службы Spooler:
Get-Service Spooler | Select DisplayName,Status,ServiceName,Can*
Командлет Get-Service имеет два параметра, которые позволяют получить зависимости служб:
- Параметр -DependentServices позволяет вывести службы, которые зависят от данной службы;
- Параметр -RequiredServices позволяет вывести службы, от которых зависит данная служба.
Приведенная ниже команда выводит службы, необходимые для запуска службе Spooler:
Get-Service –Name Spooler -RequiredServices
Следующая команда выводит службы, которые зависят от службы Spooler:
Get-Service –Name Spooler -DependentServices
При необходимости найти службы с определенным состоянием или параметрами, используйте командлет Where-Object. Например, получим список запущенных служб со статусом Running:
Get-Service | Where-Object {$_.status -eq 'running'}
Для вывода служб с типом запуска Manual, выполните команду
Get-Service | Where-Object {$_.starttype -eq 'Manual'}
Проверить, что в системе имеется указанная служба:
if (Get-Service "ServiceTest" -ErrorAction SilentlyContinue)
{
Write-host "ServiceTest exists"
}
Остановка, запуск, приостановка и перезапуск служб из PowerShell
Остановить службу можно с помощью командлета Stop-Service. Чтобы остановить службу печати, выполните команду:
Stop-Service -Name spooler
Командлет Stop-Service не выводит никаких данных после выполнения. Чтобы увидеть результат выполнения команды, используйте параметр -PassThru.
Обратите внимание, что не каждую службу можно остановить. Если есть зависимые службы, то получите ошибку
Cannot stop service because it has dependent services. It can only be stopped if force flag set.
Для принудительной остановки используйте параметр –Force. Вы должны помнить, что остановятся также все зависимые службы:
Stop-Service samss –Force -Passthru
Следующая команда остановит перечисленные службы (bits,spooler) со статусом ”Running”:
get-service bits,spooler | where {$_.status -eq 'running'} | stop-service –passthru
Командлет Start-Service запускает остановленные службы:
Start-Service -Name spooler -PassThru
Служба не запустится, если есть остановленные зависимые службы. Чтобы их найти и включить:
get-service samss | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}
Командлет Suspend-Service может приостанавливать службы, допускающие временную приостановку и возобновление. Для получения сведений о возможности временной приостановки конкретной службы используйте командлет Get-Service со свойством «CanPauseAndContinue«.
Get-Service samss | Format-List name, canpauseandcontinue
Чтобы отобразить список всех служб, работа которых может быть приостановлена, введите команду:
Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}
Приостановим службу SQLBrowser:
Suspend-Service -Name SQLBrowser
Для возобновления работы приостановленной службы служит командлет Resume-service:
Resume-Service -Name SQLBrowser
Следующая команда возобновляет работу всех приостановленных служб:
get-service | where-object {$_.Status -eq "Paused"} | resume-service
Командлет Restart-Service перезапускает службу:
Restart-Service -Name spooler
Эта команда запускает все остановленные сетевые службы компьютера:
get-service net* | where-object {$_.Status -eq "Stopped"} | restart-service
Параметр —ComputerName у этих командлетов отсутствует, но их можно выполнить на удаленном компьютере с помощью командлета Invoke-Command или через пайп:
Например, чтобы перезапустите очередь печати на удаленном компьютере RM1, выполните команду:
Get-Service Spooler -ComputerName RM1 | Start-Service
Set-Service – изменение настроек службы Windows
Командлет Set-Service позволяет изменить параметры или настройки служб на локальном или удаленном компьютере. Так как состояние службы является свойством, этот командлет можно использовать для запуска, остановки и приостановки службы. Командлет Set-Service имеет параметр -StartupType, позволяющий изменять тип запуска службы.
Изменим тип запуска службы spooler на автоматический:
Set-Service spooler –startuptype automatic –passthru
Можно перевести службу на ручной (manual) запуск:
Set-Service spooler –startuptype manual –passthru
Создание и удаление служб Windows c помощью PowerShell
New-Service – командлет для создания новой службы в Windows. Для новой службы требуется указать имя и исполняемый файл (вы можете запустить PowerShell скрипт как службу Windows).
В примере создадим новую службу с именем TestService.
new-service -name TestService -binaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
С помощью параметра Get-WmiObject получим информацию о режиме запуска и описание службы
get-wmiobject win32_service -filter "name='testservice'"
Изменить параметры новой службы можно командой
Set-Service -Name TestService -Description ‘My Service’ -StartupType Manual
Чтобы удалить службу используйте команду
(Get-WmiObject win32_service -Filter ″name=′TestService′″).delete()
Изменение учетной записи для запуска службы
Вы можете изменить учетную запись, из-под которой запускается служба. Получим имя учетной записи, которая используется для запуска службы TestService
get-wmiobject win32_service -filter "name='TestService'" | Select name,startname
Для изменения имени и пароля учетной записи выполняем команды.
$svc = get-wmiobject win32_service -filter "name='TestService'"
$svc.GetMethodParameters("change")
В результате получаем список параметров метода Change(). Считаем на каком месте находятся параметры StartName и StartPassword – 20 и 21 место соответственно.
$svc | Invoke-WmiMethod -Name Change –ArgumentList @ ($null,$null,$null,$null,$null,$null,$null, $null,$null,$null,$null,$null,$null,$null,$null,$null, $null,$null,$null,"Administrator","P@ssw0rd")
Либо вы можете указать имя gMSA аккаунта. Пароль при этом не указывается.
Как видите, PowerShell позволяет легко управлять службами Windows. Можно создавать, останавливать, запускать и возобновлять службы, менять их свойства. Большинство командлетов позволяют управлять службами на удаленных компьютерах.
Sometimes, we may need to remove Windows services installed on our PCs. For example, we may want to delete orphaned services left over after uninstalling the application running them, or you may want to delete Windows Services simply because you don’t need them.
This article discusses how to remove Windows services safely, and it is structured as follows – Section 1 discusses how to list installed services, Section 2 identifies services that are safe to remove without breaking your computer, and the last Section discusses how to remove the services we don’t want anymore.
Listing Installed Windows Services using PowerShell
The Get-Service cmdlet gets all the services in the computer. The cmdlet, by default, lists the services with three properties – Status, Name, and DisplayName.
Note that the Name property is an alias for ServiceName; therefore, we will use the two names interchangeably throughout the post. It is the property we will use most in this article to identify services.
You can also filter the services. The following commands filter items with the string “ssh” in them.
Get—Service —Name «*ssh*» |
Heads up! What Services are Safe to Stop or Delete?
Windows services can be divided into two – Microsoft services and third-party.
Most Microsoft services are not safe to be stopped or uninstalled. Any attempt to do that can crash your PC (There are a few you can remove without a serious problem).
On the other hand, most third-party services can be removed without a big problem, but you need to be careful in a few cases (we will mention them shortly).
You can identify core Windows services and third-party ones using System Configuration App.
Search for the app on the Start Menu and open it.
On the app, select the Services tab on the navigation bar, and hide the Microsoft services by checking the box at the bottom of the page. Whatever remains on the list at this point are third-party services.
The only third-party services you should not remove or stop are the ones with the words intel, display, wireless, or graphics. Intel-tagged services control many core functions of your PC; wireless services are essential for running your wireless connections; display controls the monitor behavior, and graphics are essential for the workings of graphic cards – the GPUS.
Now that we know what is safe to remove, let’s learn how to delete what we don’t want.
There are two tools you can use in this case
- sc command line tool, and
- Get-WmiObject native cmdlet
- Remove-Service cmdlet for PowerShell version 6 and above
Using the sc legacy command line utility to delete Windows service
The general syntax for removing Windows Service using sc.exe is given by:
where <service_name> is the Name of the service, not DisplayName.
Note: For older versions of PowerShell (tested on PowerShell 5.1.22), you may need to run the service control tool (sc) with the extension, that is, sc.exe. This is because sc is an alias for the Set-Content cmdlet on older PowerShell. In a newer PowerShell (tested on PowerShell 7.3.2), the alias is removed; therefore, you can simply use the command tool as sc.
Let’s identify the service we want to remove using Get-Service. In particular, let’s remove a PostgreSQL service.
Get—Service —Name «*postgre*» |
Then we can delete the service using the sc command utility.
Note: You need to run PowerShell with Admin privileges to be able to delete a service with the sc tool; otherwise, you will get the following error.
[SC] OpenService FAILED 5: Access is denied.
sc delete postgresql—x64—14 |
Output:
[SC] DeleteService SUCCESS
And use the following line on older PowerShell; you run
sc.exe delete postgresql—x64—14 |
Use Get-WmiObject native cmdlet
Here is an example of deleting a service using this cmdlet
$service = Get—WmiObject —Class Win32_Service —Filter «Name='<service_name>» $service.delete() |
Delete Windows service using the Remove-Service cmdlet
Remove-Service is available on PowerShell 6.0 and later. You can use it with this simple syntax.
Remove—Service —Name <service_name> |
That works with the Name property only. If you want to use the DisplayName, you can use the following command.
Get—Service —DisplayName «Service Name» | Remove—Service |
In the command above, the Get-Service cmdlet is used to fetch services with the “Service Name” string on the DisplayName, then pipe the result to Remove-Service to be removed.
Conclusion
This article discussed removing a Windows Service using the sc command utility, Get-WmiObject native cmdlet, and Remove-Service cmdlet. The latter is only available on PowerShell 6.0 and newer.
Have you come across a situation where uninstalling software leaves its Service or driver entries in the registry, and Windows tries to load them at every boot, fails, and logs the error to the System Event log at every startup?
This article tells you how to delete an orphaned service in Windows 10 (and earlier) using the registry, SC.exe command-line, PowerShell, or Autoruns. Before proceeding further, create a System Restore Point and take a complete Registry backup.
If you find that no dependents exist for a service, you can delete the leftover or unwanted Service in Windows using one of the following methods.
Contents
- Delete a Service in Windows
- Method 1: Using the SC.EXE command
- Method 2: Using Autoruns
- Method 3: Using the Registry Editor
- Method 4: Using PowerShell
- Method 5: Using Process Hacker
- INFO: View Dependents of a Service
You can delete a service using the built-in SC.exe command-line, the Registry Editor, PowerShell, or a utility like Autoruns. Follow one of these methods:
Using the SC command
The SC.EXE
command-line tool in Windows can be used to create, edit, or delete Services. To delete a service in Windows, use the following command-line syntax from admin Command Prompt:
sc delete service_name
Where service_name refers to the short name of the service, instead of its display name. To find the short name, open Services MMC and double-click a service.
- Example 1: Google Update Service (
gupdate
) is the display name, andgupdate
is the short name. - Example 2: Dell SupportAssist (
SupportAssistAgent
) is the display name, andSupportAssistAgent
is the short name.
Another way to find the short name of a service is by using this command-line:
sc query type= service | more
The above command lists all the services along with the service (short) name and the display name.
Or, if you know the display name, you can find the service name using this command:
sc getkeyname "service display name"
which in this example is:
sc getkeyname "Google Update Service (gupdate)"
Once the service short name is obtained using any of the above methods, use this command to delete the Service:
sc delete test
You’ll see the output: [SC] DeleteService SUCCESS
This deletes the specified service (“test” service in this example) from the computer.
If the service is running or another process has an open handle to the service, it will be marked for deletion and removed on the next reboot.
Can’t delete a service?
If you receive the following error when deleting the service, it could also be possible that you’re trying to delete a service from a normal Command Prompt instead of an admin Command Prompt.
Should the same error occur in an admin Command Prompt, then it means that the currently logged on user account doesn’t have full control permissions for that service.
[SC] OpenService FAILED 5: Access is denied.
To resolve this error when deleting a service, you need to modify the Service permissions first. Alternatively, you can use the SYSTEM or TrustedInstaller account to delete the service.
Using Autoruns from Windows Sysinternals
Autoruns, from Microsoft Windows Sysinternals, is a must-have tool that helps you manage Windows startup, services, drivers, Winsock providers, Internet Explorer add-ons, Shell extensions, etc.
- Download Autoruns and run it
- From the Options tab, tick Hide Microsoft Entries so that only the third-party entries are listed.
- Press F5 to refresh the listing.
- Click the Services tab to delete the service(s) that are unwanted or leftover.
- Close Autoruns.
Using the Registry Editor
To manually delete a service directly via the Windows Registry, use these steps:
- Start
Regedit.exe
and navigate to the following branch:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Dell SupportAssist service registry key Each sub-key under the above registry key represents a driver or a Service. The key name is the same as the short name of the service. Also, you should be able to identify the entry easily by looking at the DisplayName and ImagePath values in the right pane in the Registry Editor.
- Find the entry you want to delete.
- Backup the appropriate key by exporting it to a .reg file.
- Once exported, right-click the key, and choose Delete.
- Exit the Registry Editor.
Using PowerShell
From the PowerShell administrator window, you can use the following commands to delete a service.
$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'" $service.delete()
ReturnValue of 0
indicates that the operation was successful. The service is deleted and will no longer show up in the Services MMC.
To know the meaning of a return value, check out the Microsoft article Delete method of the Win32_Service class
Or you can run the sc.exe command in PowerShell. That would work too. But you need to specify the extension (
sc.exe
) when running it in PowerShell. This is because the command SC
(without mentioning the extension .exe
) will be interpreted as Set-Content
which is a built-in cmdlet in PowerShell.
It’s even easier if you have PowerShell 6.0 installed. In PowerShell 6 and higher, you can use this syntax to remove a service:
Remove-Service -Name ServiceName
Running the Remove-Service
command in older versions of PowerShell (<6.0) shows the error: The term ‘Remove-Service’ is not recognized as the name of a cmdlet, function, script file, or operable program.
Using Process Hacker
Process Hacker is a good process management utility that is similar in appearance to Microsoft’s Process Explorer. With Process Hacker, you can easily delete a service via the right-click menu.
Start Process Hacker as administrator. Switch to the Services tab, right-click on the service you want to remove, and click Delete.
(As a side note, you can also configure service permissions using Process Hacker.)
Download Process Hacker from https://processhacker.sourceforge.io/
View Dependents of a Service
When you remove a service, others that depend upon the service will fail to start, returning the error “System error 1075 has occurred. The dependency service does not exist or has been marked for deletion.”. When a driver or service entry is leftover in the registry, but the corresponding files are missing, the Event Log would record an entry with ID:7000
at every start.
Log Name: System Source: Service Control Manager Date: Event ID: 7000 Level: Error Description: The DgiVecp service failed to start due to the following error: The system cannot find the file specified.
So, it’s advisable first to check if there are any dependents. You can check that in Services MMC by double-clicking on the item you’re going to delete and clicking the Dependencies tab. The list of components that depend on that service is shown below. Here is an example where “Fax” depends on “Print Spooler” to start.
While most third-party services don’t have any dependents, some do. It’s always advisable to take a look at this tab before clearing the item.
Another way to verify the dependents is to run this command from a Command Prompt window. (example, Print Spooler)
sc enumdepend spooler
The information in this article applies to all versions of Windows, including Windows 11.
One small request: If you liked this post, please share this?
One «tiny» share from you would seriously help a lot with the growth of this blog.
Some great suggestions:
- Pin it!
- Share it to your favorite blog + Facebook, Reddit
- Tweet it!
So thank you so much for your support. It won’t take more than 10 seconds of your time. The share buttons are right below.