Force stop service windows

Как завершить процесс службы Windows, которая зависла в статусе stopping (остановка) или starting (запуск)? Большинство администраторов Windows встречалось с ситуациями, когда при попытке остановить (перезапустить) службу из графического интерфейса консоли управления службами (
Services.msc
), служба зависает намертво и висит в статусе Stopping (или Starting). При этом все кнопки управления службой в консоли (Start, Stop, Restart) становятся недоступными (серыми). Самый простой способ – перезагрузить сервер, но это не всегда допустимо. Рассмотрим альтернативные способы, позволяющие принудительно завершить зависшую службу или процесс без необходимости перезагрузки Windows.

служба windows зависла в статусе stopping и не выключается

Если в течении 30 секунд после попытки остановки службы, она не останавливается, Windows выводит сообщение:

Не удалось остановить службу xxxxxxx Windows на локальном компьютере.
 Ошибка 1053. Служба не ответила на запрос своевременно.
Windows Could not stop the xxxxxx service on Local Computer
Error 1053: The service did not respond in a timely fashion.

При попытке остановить такую службу командой:
net stop wuauserv
, появляется сообщение:

The service is starting or stopping. Please try again later.

net stop The service is starting or stopping. Please try again letter.

Или:

[SC] ControlService: ошибка: 1061:
Служба в настоящее время не может принимать команды.
Windows could not stop the Service on Local Computer.
Error 1061: The service cannot accept control messages at this time.

Содержание:

  • Как остановить зависшую службу Windows из командной строки?
  • Принудительное завершение зависшей службы в PowerShell
  • Анализ цепочки ожидания зависшего приложения с помощью ResMon
  • Process Explorer: Завершение зависшего процесса из-под SYSTEM

Как остановить зависшую службу Windows из командной строки?

Самый простой способ завершить зависшую служу – воспользоваться утилитой taskkill. В первую очередь нужно определить PID (идентификатор процесса) нашей службы. В качестве примера возьмем службу Windows Update. Ее системное имя wuauserv (имя можно посмотреть в свойствах службы в консоли
services.msc
).

Важно. Будьте внимательными. Принудительная отставка процесса критичной службы Windows может привести к BSOD или перезагрузке операционной системы.

Отройте командную строку с правами правами администратора (иначе будет ошибка access denied) и выполите команду:
sc queryex wuauserv

В данном случае PID процесса —
9186
.

Чтобы принудительно завершить зависший процесс с PID 9186 воспользуйтесь утилитой taskkill:

taskkill /PID 9168 /F

завершить зависшую службу из командной строки с помощью утилиты taskkill

SUCCESS: The process with PID 9168 has been terminated.

Данная команда принудительно завершит процесс службы. Теперь вы можете запустите службу командой sc start servicename или через консоль управления службами (или совсем удалить эту службу, если она не нужна).

«Выстрел в голову» зависшей службы можно выполнить и более элегантно, не выполняя ручное определение PID процесса. У утилиты taskkill есть параметр /FI, позволяющий использовать фильтр для выбора необходимых служб или процессов. Вы можете остановить конкретную службу командой:

TASKKILL /F /FI “SERVICES eq wuauserv”

Или можно вообще не указывать имя, службы, завершив все сервисы в зависшем состоянии с помощью команды:

taskkill /F /FI “status eq not responding”

После этого служба, зависшая в статусе Stopping должна остановиться.

Также вы можете использовать утилиту taskkill для принудительной остановки зависших служб на удаленном компьютере:

TASKKILL /S CORPFS01 /F /FI “SERVICES eq wuauserv”

Принудительное завершение зависшей службы в PowerShell

Также вы можете использовать PowerShell для принудительной остановки службы. С помощью следующей команды можно получить список служб, находящихся в состоянии Stopping:

Get-WmiObject -Class win32_service | Where-Object {$_.state -eq 'stop pending'}

poweshell список служб в статусе stop pending

Завершить процесс для всех найденных служб поможет командлет Stop-Process. Следующий PowerShell скрипт завершит все процессы зависших служб в Windows:

$Services = Get-WmiObject -Class win32_service -Filter "state = 'stop pending'"
if ($Services) {
foreach ($service in $Services) {
try {
Stop-Process -Id $service.processid -Force -PassThru -ErrorAction Stop
}
catch {
Write-Warning -Message " Error. Error details: $_.Exception.Message"
}
}
}
else {
Write-Output "No services with 'Stopping'.status"
}

powershell скрипт для принудительной остановки всех зависших служб

В новом PowerShell Core 6.x/7.x вместо командлета Get-WmiObject нужно использовать Get-CimInstance. Замените первую команду скрипта на:

$Services = Get-CimInstance -Class win32_service | where-Object state -eq 'stop pending'

Анализ цепочки ожидания зависшего приложения с помощью ResMon

Вы можете определить процесс, из-за которого зависла служба с помощью монитора ресурсов (
resmon.exe
).

  1. В окне Монитора ресурсов перейдите на вкладку ЦП (CPU) и найдите процесс зависшей службы;
  2. Выберите пункт Анализ цепочки ожидания (Analyze Wait Chain);
    resmon анализ цепочки ожидания зависшей службы

  3. В новом окне скорее всего вы увидите, что вам процесс ожидает другой процесс. Завершите его. Если выполняется ожидание системного процесса svchost.exe, завершать его не нужно. Попробуйте проанализировать цепочку ожидания для этого процесса. Найдите PID процесса, которого ожидает ваш svchost.exe и завершите его

Process Explorer: Завершение зависшего процесса из-под SYSTEM

Некоторые процессы, запущенные из-под SYSTEM, не может завершить даже локальный администратора сервера. Дело в том, что у него просто может не быть прав на некоторые процессы или службы. Чтобы завершить такие процесс (службы), вам необходимо предоставить локальной группе Administrators права на службу (процесс), а потом завершить их. Для этого нам понадобятся две утилиты: psexec.exe и ProcessExplorer (доступны на сайте Microsoft).

  1. Чтобы запустить утилиту ProcessExplorer с правами системы (SYSTEM), выполните команду:
    PSExec -s -i ProcExp.exe
  2. В списке процессов Process Explorer найдите процесс зависшей службы и откройте ее свойства;
  3. Перейдите на вкладку Services, найдите свою службу и нажмите кнопку Permissions;
    procexplorer - задать права на службу

  4. В разрешения службы предоставьте права Full Control для группы администраторов (Administrators). Сохраните изменения;
  5. Теперь попробуйте завершить процесс службы.

    Обратите внимание, что права на службу и ее процесс выдались временно, до ее перезапуска. Для предоставления постоянных прав на службы познакомьтесь со статьей Права на службы в Windows.

Таймаут, в течении которого Service Control Manager ждет ожидания запуска или остановки службы можно изменить через параметр реестра ServicesPipeTimeout. Если служба не запускается в течении указанного таймаута, Windows записывает ошибку в Event Log (Event ID: 7000, 7009, 7011, A timeout was reached 30000 milliseconds). Вы можете увеличить этот таймаут, например до 60 секунд:

reg add HKLM\SYSTEM\CurrentControlSet\Control /v ServicesPipeTimeout /t REG_SZ /d 600000 /f

Это бывает полезным при запуске/остановки тяжелых служб, которые не успевают завершить все процессы быстро (например, MS SQL Server).

служба mssql зависает при запуске

To forcefully stop a service using the Command Prompt, you can use the `sc stop` command followed by the service name. Here’s how you can do it:

sc stop "ServiceName"

Replace `»ServiceName»` with the actual name of the service you wish to stop.

Understanding Windows Services

What is a Windows Service?

A Windows Service is a long-running application that runs in the background without user intervention. Unlike standard applications that may be visible to users, services operate silently and typically handle tasks such as security, server operations, and system management. Common examples of Windows services include:

  • Windows Update — Manages the download and installation of Windows updates.
  • Print Spooler — Responsible for managing print jobs sent to the printer.
  • Background Intelligent Transfer Service (BITS) — Facilitates file transfers in the background without disrupting the user’s network experience.

Reasons to Stop a Windows Service

There are several valid reasons for stopping a Windows service:

  • Troubleshooting and Diagnostics: If an application is malfunctioning, you may need to stop its associated service to troubleshoot the issue.
  • Resource Management: Stopping unnecessary services can free up system resources, enhancing overall performance.
  • Application Updates and Maintenance: Some applications require their services to be halted during updates or maintenance routines to avoid conflicts.

Cmd Delete Service: A Quick Tutorial for Beginners

Cmd Delete Service: A Quick Tutorial for Beginners

Using CMD to Stop a Windows Service

Introduction to CMD Commands

The Command Prompt (CMD) is a command-line interpreter available in Windows that allows users to execute commands for managing the operating system and its components. CMD commands follow a straightforward syntax, which usually consists of the command itself followed by its parameters.

Basic Command to Stop a Service

The simplest way to stop a service via CMD is by utilizing the `net stop` command. This command halts a running service gracefully.

Example Command:

net stop "ServiceName"

Replace `»ServiceName»` with the actual name of the service you wish to stop. It’s important to note that the service name is often different from the display name visible in the Services management console.

Cmd Kill Service: A Simple Guide to Command Mastery

Cmd Kill Service: A Simple Guide to Command Mastery

Force Stopping a Windows Service with CMD

Why Force Stop a Service?

A service may not respond to the `net stop` command due to various reasons, such as being hung or not terminating properly. In these instances, you may need to forcefully stop the service to restore system functionality. However, be cautious—force stopping can lead to data loss if the service is performing critical operations.

How to Force Stop a Service in CMD

To force stop a service, you can use the `sc` command, which provides more control over Windows services. The syntax for forcefully stopping a service is as follows:

sc stop "ServiceName"

This command tells the service to stop immediately. However, if the service continues to run, another method is to use the `taskkill` command to terminate the associated process directly.

Example of Force Stopping a Service

  1. Open CMD as Administrator: Right-click on the Command Prompt icon and select Run as Administrator. This is essential for executing commands requiring elevated privileges.

  2. Use the `sc query` Command: Before you stop a service, it’s good practice to verify its status and make sure you have the correct name. You can list all services with:

    sc query
    
  3. Issue the Force Stop Command: After confirming the service name, you can issue the command to stop it:

    sc stop "ServiceName"
    
  4. Confirmation Message Interpretation: The command will return a message indicating whether the service has been successfully stopped or if there were issues in the process.

Cmd Force Group Policy Update: A Quick Guide

Cmd Force Group Policy Update: A Quick Guide

Commands for Verifying Service Status

Checking Active Services

To get an overview of all running services, execute the following command:

sc query type= service state= all

This command displays the status of all services, allowing you to find out which ones are currently active.

Confirming Service Stop

To check if a specific service has been successfully stopped, you can run:

sc query "ServiceName"

The output will provide the current state of the specified service (e.g., RUNNING or STOPPED). Confirm that the desired service status is reflected correctly.

Master Cmd Minecraft Server Commands Quickly and Easily

Master Cmd Minecraft Server Commands Quickly and Easily

Troubleshooting Common Issues

Errors When Stopping a Service

When attempting to stop a service via CMD, you may encounter errors. Some common error messages include:

  • Error 1053: The service did not respond to the start or control request in a timely fashion: This usually indicates that the service is hung or has failed to respond.

If you encounter an error, try restarting your system or assessing the service dependencies to ensure they’re not hindering the stop command.

Alternative Tools and Commands

If CMD proves ineffective, consider using PowerShell, which offers a more modern command-line experience. The `Stop-Service` cmdlet allows you to stop services with more straightforward syntax:

Stop-Service -Name "ServiceName"

Knowing when to use CMD versus PowerShell can streamline your service management processes.

Cmd Force Shutdown: Quick Guide to Command Line Power

Cmd Force Shutdown: Quick Guide to Command Line Power

Conclusion

In this guide, you’ve learned how to effectively use CMD to force stop a Windows service. Mastering these commands can significantly enhance your ability to manage Windows services and troubleshoot issues that may arise. By familiarizing yourself with CMD and the various commands available, you can ensure more efficient use of your Windows operating system.

As you continue your journey with CMD, don’t hesitate to explore additional commands and their functions to broaden your capabilities in service management and other Windows operations.

Время на прочтение8 мин

Количество просмотров116K

Продолжаем знакомиться с тем, как осуществлять управление службами Windows с использованием PowerShell. В предыдущем посте мы рассмотрели, как получить статус службы на локальном и удаленном компьютере, произвести фильтрацию служб (например, найти только остановленные службы) и определить зависимые службы. В этом посте будут рассмотрены такие достаточно тривиальные вещи, как:

  1. Остановка службы
  2. Запуск службы
  3. Перезапуск службы
  4. Приостановка и возобновление работы
  5. Управление удаленными службами
  6. Настраиваем автозагрузку службы

Мы уделим большее внимание разбору команд в PowerShell для осуществления выше перечисленного на локальном компьютере. В разделе “управление службами удаленных компьютерах” мы рассмотрим, ограничения работы в PowerShell v2 и v3. Подробности под катом.

Предыдущая статья:
Управляем службами Windows с помощью PowerShell. Часть 1. Получаем статус служб

PS C:\> get-service bits
Status Name DisplayName
------ ---- -----------
Running bits Background Intelligent Transfer Ser...

Так как команда для получения статуса службы называется Get-Service, догадаться о том, как пишутся другие команды не составит труда. На худой конец мы можем спросить у PowerShell обо всех командах, так или иначе относящихся к работе со службами. Обратите внимание, что мы использовали параметр –noun для получения всех команд, связанных со службами.

Взглянем на эти команды внимательнее.

STOP-SERVICE

Чтобы остановить службу, мы должны уточнить ее имя.

PS C:\> stop-service wuauserv

Однако в конвейер ничего не будет передано. Некоторые командлеты, такие как Stop-Service, созданы таким образом, что по умолчанию они не записывают объект в конвейер. Мы же заставим это сделать, использовав параметр –Passthru.

PS C:\> stop-service bits -PassThru
Status Name DisplayName
------ ---- -----------
Stopped bits Background Intelligent Transfer Ser...

Если служба не запущена, то командлет ничего не выведет, равно как и не выдаст никакой ошибки. Поэтому иногда лучше передать объект в Stop-Service (естественно использовав при этом параметр –whatif).

PS C:\> get-service browser | stop-service -WhatIf
What if: Performing operation “Stop-Service” on Target “Computer Browser (browser)”.

Параметр –WhatIf был добавлен для того, чтобы мы посмотрели, что будет, если командлет будет запущен. Когда я удостоверюсь, что это именно та служба, которая меня интересует, я просто удалю -Whatif и остановлю службу.

PS C:\> get-service browser | stop-service

Как я уже упомянул выше, если служба уже остановлена, то командлет ничего не сделает. И использование Stop-Service в этом случае никому не навредит. Однако я все же предпочитают более цивилизованный подход, а именно:

PS C:\> get-service bits | where {$_.status -eq 'running'} | stop-service -pass
Status Name DisplayName
------ ---- -----------
Stopped bits Background Intelligent Transfer Ser...

Если служба запущена, то объект передается в конвейер и отправляется в Stop-Service. Ниже приведен вариант с остановкой нескольких служб.

PS C:\> get-service bits,wsearch,winrm,spooler | where {$_.status -eq 'running'} | stop-service -whatif
What if: Performing operation "Stop-Service" on Target "Print Spooler (spooler)".
What if: Performing operation "Stop-Service" on Target "Windows Remote Management (WS-Management) (winrm)".
What if: Performing operation "Stop-Service" on Target "Windows Search (wsearch)".

Некоторые службы не захотят останавливаться – в силу наличия зависимых служб – что мы и видим на скриншоте ниже.

В таком случае используем параметр –Force. В большинстве случаев это работает, но без “защиты от дурака”. Помните, что команда также остановит зависимые службы.

PS C:\> stop-service lanmanserver -force –PassThru
Status Name DisplayName
------ ---- -----------
Stopped Browser Computer Browser
Stopped lanmanserver Server

START-SERVICE

Запуск службы осуществляется аналогичным образом. Он поддерживает параметр –Whatif, и вам придется использовать –Passthru, чтобы увидеть объекты.

PS C:\> start-service wuauserv -PassThru
Status Name DisplayName
------ ---- -----------
Running wuauserv Windows Update

И снова: если служба уже запущена, командлет ничего не сделает. Однако вы можете попытаться запустить службу и получите такую ошибку.

Причиной тому в большинстве случаев является выключенные службы. Как конфигурировать настройки службы, я расскажу в следующей статье.
Если вы хотите запустить службы и все службы, зависимые от нее, используйте следующее выражение:

PS C:\> get-service lanmanserver | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}
Status Name DisplayName
------ ---- -----------
Running lanmanserver Server
Running Browser Computer Browser

Мы должны явно получить зависимые службы, потому что Start-Service не запустит автоматически их.

RESTART-SERVICE

Вы удивитесь, но перезапуск службы работает также как два предыдущих примера. Используйте –Passthru, если хотите убедиться, что служба запущена.

PS C:\> restart-service spooler -PassThru
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler

Так как мы осуществляем остановку службы, нам может понадобиться параметр –Force.

ПРИОСТАНОВКА И ВОЗОБНОВЛЕНИЕ РАБОТЫ

Работа некоторых служб может быть приостановлена на некоторое время, а затем возобновлена, и мы можем это сделать через PowerShell. Однако если служба не удовлетворяет требованиям, мы получим такие ошибки. (на примере показано, что мы пытались приостановить службу bits)

В чем же проблема? Смотрим на объект (используя Get-Service).

PS C:\> get-service bits | select *
Name : bits
RequiredServices : {RpcSs, EventSystem}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
DisplayName : Background Intelligent Transfer Service
DependentServices : {}
MachineName : .
ServiceName : bits
ServicesDependedOn : {RpcSs, EventSystem}
ServiceHandle : SafeServiceHandle
Status : Running
ServiceType : Win32ShareProcess
Site :
Container :

Если значение свойства CanPauseAndContinue равно True, значит мы можем приостанавливать и возобновлять работу службы. Найдем такие службы:

PS C:\> get-service | where {$_.CanPauseandContinue}
Status Name DisplayName
------ ---- -----------
Running LanmanServer Server
Running LanmanWorkstation Workstation
Running MSSQLSERVER SQL Server (MSSQLSERVER)
Running O2FLASH O2FLASH
Running stisvc Windows Image Acquisition (WIA)
Running Winmgmt Windows Management Instrumentation

Как мы видим, не так много служб удовлетворяют этому требованию.

PS C:\> suspend-service o2flash -PassThru
Status Name DisplayName
------ ---- -----------
Paused O2FLASH o2flash

Готовы возобновить работу службы? Используйте следующее выражение:

PS C:\> resume-service o2flash -PassThru
Status Name DisplayName
------ ---- -----------
Running O2FLASH o2flash

Оба командлета также поддерживают –Whatif.

УДАЛЕННЫЕ СЛУЖБЫ

Как вы могли обратить внимание, все примере выше мы демонстрировали на локальном машине. И это неслучайно. К сожалению даже в PowerShell v3, ни у одного из этих командлетов нет параметра, который позволял бы управлять службой на удаленном компьютере. Get-Service, конечно, поддерживает параметр –Computername, но не более. Службу лицезреть вы сможете, а что-либо с ней сделать не получится. Нет, можно, конечно, если удаленный компьютер работает с PS v2 и включен PowerShell Remoting. Тогда мы можете использовать все выше приведенные команды, используя Invoke-Command для удаленного компьютера или PSSession. С другой стороны, проще управлять одной службой на нескольких серверах.

PS C:\> Invoke-Command {restart-service dns –passthru} –comp chi-dc03,chi-dc02,chi-dc01

Управление службами на удаленных компьютерах не ограничивается вышеперечисленным, но это уже будет предмет рассмотрения последующих статей.
Все эти командлеты могут быть использованы в конвейерном выражении и зачастую это лучший вариант. Использование Get-Service для получения объектов и последующая передача их в подходящий командлет.

УСТАНАВЛИВАЕМ УДАЛЕННЫЙ СТАТУС

Итак, мы выяснили, что у командлета Stop-Service отсутствует такой полезный параметр как –Computername. Мы можете использовать эти команды в удаленной сессии, обратившись к командлету Invoke-Command, что уже само по себе продуктивно, если вы работаете со службой на нескольких компьютерах. Одно можно запускать, останавливать, перезапускать, ставить на паузу и запускать заново, используя Set-Service.

PS C:\> set-service wuauserv -ComputerName chi-dc03 -Status stopped -WhatIf
What if: Performing operation "Set-Service" on Target "Windows Update (wuauserv)".

Эта команда поддерживает параметр –WhatIf. Вы также должны использовать –Passthru для передачи объектов в конвейер.

PS C:\> set-service bits -ComputerName chi-dc03 -Status running -PassThru
Status Name DisplayName
------ ---- -----------
Running bits Background Intelligent Transfer Ser...

Валидными значениям для параметра –Status являются “запущена” (running), “остановлена” (stopped) и “на паузе” (paused). Помните, что у службы есть зависимые службы, мы не сможете изменять ее, что и продемонстрировано на скриншоте ниже.

К сожалению, у Set-Service отсутствует параметр –Force, поэтому придется вернуться к использованию PowerShell remoting и Invoke-Command. Если вы хотите перезапустить удаленную службу, используйте следующую команду:

PS C:\> set-service w32time -ComputerName chi-dc03 -Status Stopped -PassThru | set-service -PassThru -Status Running
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time

Не забудьте использовать –Passthru, в противном случае вторая команда Set-Service ничего не осуществит.
Что по мне, так я предпочитаю работать сразу с несколькими службами, которые я не могу удаленно остановить, используя Set-Service, хотя их запуск проблем составляет. Я использую Invoke-Command. Но помните, что используя параметр –Computername PowerShell осуществляет подключение, используя RPC и DCOM, что может привести к проблемам с файрволом. Invoke-Command использует PowerShell remoting, который мы может быть еще не настроили или не включили.

УСТАНАВЛИВАЕМ ТИП АВТОЗАПУСКА СЛУЖБЫ

Set-Service полезнен, когда вы хотите включить или отключить службу, используя параметр –StartupType. Если Вы настроили службу, используя значения Automatic, Manual or Disabled. К сожалению, не существует варианта для Automatic (Delayed).

PS C:\> set-service remoteregistry -StartupType Manual -WhatIf
What if: Performing operation "Set-Service" on Target "Remote Registry (remoteregistry)".
PS C:\> set-service remoteregistry -StartupType Manual -PassThru
Status Name DisplayName
------ ---- -----------
Stopped remoteregistry Remote Registry

Однако, просто взглянув на объект, мы не сможем сказать, к какому типу автозагрузки он относится.

PS C:\> get-service remoteregistry | select *
Name : remoteregistry
RequiredServices : {RPCSS}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
DisplayName : Remote Registry
DependentServices : {}
MachineName : .
ServiceName : remoteregistry
ServicesDependedOn : {RPCSS}
ServiceHandle : SafeServiceHandle
Status : Stopped
ServiceType : Win32ShareProcess
Site :
Container :

Как это сделать – одна из тем следующей статьи.
Помните, что изменение типа автозагрузки не повлияет на текущий статус службы.

PS C:\> set-service remoteregistry -StartupType Disabled -PassThru
Status Name DisplayName
------ ---- -----------
Running remoteregistry Remote Registry

Так что если вы хотите выключить и остановить (или включить и запустить) службу, передайте объект в подходящий командлет.

PS C:\> set-service remoteregistry -StartupType Disabled -PassThru | Stop-Service -PassThru
Status Name DisplayName
------ ---- -----------
Stopped remoteregistry Remote Registry

Технически, Set-Service позволяет вам изменить отображаемое имя службы и описание, но лично мне никогда не приходилось использовать в своей работе. Я использую Set-Service для включения и выключения служб. Если необходимо управлять службами удаленно, то я использую Invoke-Command.
Все, что я продемонстрировал в последних статьях, было связано с использованием специфических типов объектов службы, которые, как вы могли заметить, имеют некоторые ограничения. В следующей статье мы рассмотрим другие возможности по управлению службами, которые призваны обойти эти ограничения.

Upd:
В посте приведены переводы статей с портала 4sysops.com
Managing Services the PowerShell way – Part 3
Managing Services the PowerShell way – Part 4

Being a Windows Server Administrator, you certainly have several responsibilities towards the job. You need to be in control of the things in order to keep running everything smoothly. Even a trivial possibility of anything going wrong should be dealt with utter diligence.

Now, during a normal day at work, you might come across a stubborn Windows Service which is stuck at starting/stopping state since what seems like an eternity. At such a moment of crisis, you would want to make a decision of killing the service in order to avoid rebooting the server in middle of the noontide.

Considering the normal case scenario, any service could hang, be it a deadlock situation or the resource limitation. Although, it might frequently happen in application services such as Microsoft Exchange (POP3 and IMAP). You can use the TaskKill command to terminate the culprit service and avoid the reboot mechanism in middle of business hours.

Here’s how to do so :

How To Force Stop A Windows Service Using Command Prompt In Windows 10/8.1/8/7

1. Press  + R and type services.msc in the Run dialog box, hit Enter key to open Services snap-in.

2. Now on the right side pane of Services, search for the service by its name. For instance, if you are looking for Microsoft Passport service, find it by scrolling down to the corresponding name and double-click it.

How To Force Stop A Service Using Command Prompt Windows 10

3. In the service property sheet shown below, note down Service Name on the top in General tab. Remember this name as it will be used to find its PID (Process ID) and kill the task. You can see here that I can’t stop the Microsoft Passport service, as the Stop button is not active.

How To Force Stop A Service Using Command Prompt Windows 10

4. Open administrative Command Prompt and type this command after substituting the <SERVICENAME> with actual service name you noticed in step 3.

sc queryex <SERVICENAME>

5. From the results of the above query, make a note of PID.

How To Force Stop A Service Using Command Prompt Windows 10

6. On the same Command Prompt window, type the following, where PID is the Process ID you just copied, and hit Enter.

taskkill /f /pid PID

How To Force Stop A Service Using Command Prompt Windows 10

This will kill the culprit service forcibly and put it on rest. In case you later need to start the service, you can do it simply from service property sheet shown in step 3.

That’s it!

RELATED ARTICLES

In Windows, sometimes a service may become unresponsive or stuck and cannot be stopped using the usual net stop or Task Manager methods. In such cases, you can force kill the service using the taskkill command. This tutorial will guide you through the process of force killing a service on Windows.

The Problem

In our AWS Windows server, the Amazon SSM Agent service was stuck during startup. The service status kept showing “starting” all the time.

Unresponsive Windows Service

Unresponsive Windows Service

The only option was to forcefully kill this service by the process ID on the Windows system. Below instructions will help you with it.

Step-by-Step Solution

Follow the below steps to find PID of service and forcefully terminate that.

  1. Find the Service name
  2. Right-click on the service and open properties. Here you will find the service name under the General tab. For example, view the below screenshot.

    Find Windows Service Name

    Find Windows Service Name

    In my case, the service name is AmazonSSMAgent.

  3. Find the PID
  4. Then execute the below command with the service name identified above.

    
    sc queryex [servicename]
    
    

    This will show you the service details on the console as below.

    Check Windows Service PID

    Checking PID of Windows Service

  5. Kill Process by PID
  6. Find out the service’s PID (process ID) and force kill the process by using the command below. Use the PID number found with the previous command.

    
    taskkill /f /pid <PID>
    
    

    Replace with the actual Process ID of the service you want to force kill.

    Kill Windows Service by PID

    Kill Windows Service by PID

All done. You can now start your service again.

Conclusion

Using the taskkill command to force stop a service is a quick way to deal with unresponsive or stuck services on Windows. However, it should only be used as a last option because it can cause data loss or other problems if not done correctly. Always save your important data before you try to force stop a service, and only use this method if other ways to stop the service have not worked.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не работает sonicmaster windows 10
  • Ошибка при запуске приложения 0xc000005 windows 7
  • Яркие цвета windows 10
  • Windows 10 pro get genuine for oem software как активировать
  • Как проверить поддержку windows 11