- Killing a Windows Service that Hangs on Stopping or Not Responding
- How to Terminate a Hung Windows Service Process Using TaskKill?
- PowerShell: Stop Windows Service with Stopping Status
- Identify a Hang Process Using Resmon
- Process Explorer: Killing a Hung Process Running in SYSTEM Context
- Stop-Service
- Syntax
- Description
- Examples
- Example 1: Stop a service on the local computer
- Example 2: Stop a service by using the display name
- Example 3: Stop a service that has dependent services
- Parameters
- Inputs
- Outputs
- Notes
- Управление службами Windows с помощью PowerShell
- Основные командлеты PowerShell для управления службами Windows
- Остановка, запуск, приостановка и перезапуск служб из PowerShell
- Set-Service – изменение настроек службы Windows
- Создание и удаление служб Windows c помощью PowerShell
- Изменение учетной записи для запуска службы
Killing a Windows Service that Hangs on Stopping or Not Responding
How to manually forcefully stop a hung Windows service process that hangs at “Stopping” or “Not responding”? Most Windows administrators have faced a problem, when they try to stop (restart) a service, but it gets stuck with the Stopping status. You won’t be able to stop this service from the Service management console (services.msc), since all control buttons for this service become inactive. The easiest way is to restart Windows, but it is not always acceptable. Let’s consider an alternative way, which allows to forcefully kill a stuck Windows service or process without system reboot.
If within 30 seconds after trying to stop the service, it doesn’t stop, Windows displays this message:
If you try to stop such a service from the command prompt: net stop wuauserv , a message appears:
The service is starting or stopping. Please try again letter.
How to Terminate a Hung Windows Service Process Using TaskKill?
The easiest way to stop a stuck service is to use taskkill. First of all, you need to find the PID (process identifier) of the service. As an example, let’s take Windows Update service, its system name is wuauserv (you can check the name in the service properties in the services.msc console).
Run this command in the elevated command prompt (it is important, or access denied error will appear):
sc queryex wuauserv
In our case the PID of the wuauserv service is 816.
To force stop a hung process with the PID 816, run the command:
taskkill /PID 816 /F
You can stop a hung service more elegantly without checking the service PID manually. The taskkill utility has the /FI option, which allows you to use a filter to select the necessary services or processes. You can shutdown a specific service with the command:
taskkill /F /FI «SERVICES eq wuauserv»
Or you can skip the service name at all and killing all services in a hung state with the command:
taskkill /F /FI «status eq not responding»
After this, the service that hangs in the Stopping status should stop.
PowerShell: Stop Windows Service with Stopping Status
You can also use PowerShell to force the service to stop. Using the following command you can get a list of services in the Stopping state:
Get-WmiObject -Class win32_service | Where-Object
The Stop-Process cmdlet allows to terminate the processes of all found services. Let’s combine both operations into a loop and get a script that automatically terminates all the processes of the stuck services:
$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»
>
Identify a Hang Process Using Resmon
You can detect the process that caused the service freeze using the resmon (Resource Monitor).
- In the Resource Monitor window, go to the CPU tab and locate the hung service process;
- Select the item Analyze Wait Chain from the context menu;
- In the new window, you will most likely see that your process is waiting for another process. End the process. If you are waiting for the svchost.exe or another system process, you don’t need to terminate it. Try to analyze the wait chain for this process. Find the PID of the process that your svchost.exe is waiting for and kill it.
Process Explorer: Killing a Hung Process Running in SYSTEM Context
Even the local administrator cannot terminate some processes that run in the SYSTEM context. The fact is that the admin account simply haven’t permissions on some processes or services. To stop such a process (services), you need to grant permissions to the service (process) to the local Administrators group, and then terminate them. To do this, we will need two small tools: psexec.exe and ProcessExplorer (available on the Microsoft website).
- To run ProcessExplorer with the system privileges (runas SYSTEM), run the utility in this way: PSExec -s -i ProcExp.exe
- In the Process Explorer process list, find the stuck service process and open its properties;
- Go to the Services tab, find your service and click the Permissions button;
- Grant the Full Control right in the service permissions for the Administrators group. Save the changes;
- Now try to stop the service process.
Stop-Service
Stops one or more running services.
Syntax
Description
The Stop-Service cmdlet sends a stop message to the Windows Service Controller for each of the specified services. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass a service object that represents the service that you want to stop.
Examples
Example 1: Stop a service on the local computer
This command stops the Performance Logs and Alerts (SysmonLog) service on the local computer.
Example 2: Stop a service by using the display name
This command stops the Telnet service on the local computer. The command uses Get-Service to get an object that represents the Telnet service. The pipeline operator ( | ) pipes the object to Stop-Service , which stops the service.
Example 3: Stop a service that has dependent services
This example stops the IISAdmin service on the local computer. Because stopping this service also stops the services that depend on the IISAdmin service, it is best to precede Stop-Service with a command that lists the services that depend on the IISAdmin service.
The first command lists the services that depend on IISAdmin. It uses Get-Service to get an object that represents the IISAdmin service. The pipeline operator ( | ) passes the result to the Format-List cmdlet. The command uses the Property parameter of Format-List to list only the Name and DependentServices properties of the service.
The second command stops the IISAdmin service. The Force parameter is required to stop a service that has dependent services. The command uses the Confirm parameter to request confirmation from the user before it stops each service.
Parameters
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the display names of the services to stop. Wildcard characters are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies services that this cmdlet omits. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Forces the cmdlet to stop a service even if that service has dependent services.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies services that this cmdlet stops. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies ServiceController objects that represent the services to stop. Enter a variable that contains the objects, or type a command or expression that gets the objects.
Type: | ServiceController [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the service names of the services to stop. Wildcard characters are permitted.
Type: | String [ ] |
Aliases: | ServiceName |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Indicates that this cmdlet uses the no wait option.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Returns an object that represents the service. By default, this cmdlet does not generate any output.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
System.ServiceProcess.ServiceController, System.String
You can pipe a service object or a string that contains the name of a service to this cmdlet.
Outputs
None, System.ServiceProcess.ServiceController
This cmdlet generates a System.ServiceProcess.ServiceController object that represents the service, if you use the PassThru parameter. Otherwise, this cmdlet does not generate any output.
Notes
This cmdlet is only available on Windows platforms.
You can also refer to Stop-Service by its built-in alias, spsv. For more information, see about_Aliases.
Stop-Service can control services only when the current user has permission to do this. If a command does not work correctly, you might not have the required permissions.
To find the service names and display names of the services on your system, type Get-Service . The service names appear in the Name column and the display names appear in the DisplayName column.
Управление службами Windows с помощью PowerShell
В Windows вы можете управлять службами не только из графической консоли services.msc или утилиты командной строки Sc.exe (первоначальна включалась в пакет ресурсов Resource Kit), но и с помощью PowerShell. В этой статье мы смотрим различные сценарии управления службами Windows с помощью PowerShell.
Основные командлеты PowerShell для управления службами Windows
Существует восемь основных командлетов Service, предназначенных для просмотра состояния и управления службами Windows.
Чтобы получить весь список командлетов 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-Service: получаем список служб и их состояние
Получить список и состояние (Running/Stopped) службы на локальном или удаленном компьютере можно с помощью командлета Get-Service. Параметр -Name позволяет делать отбор по имени службы. Имя службы можно задать с использованием подстановочного символа *.
Если вы не знаете точное имя службы, есть возможность найти службы по отображаемому имени с помощью параметра –DisplayName. Можно использовать список значений и подстановочные знаки.
.
Командлет Get-Service можно использовать для получения состояния служб на удаленных компьютерах, указав параметр -ComputerName. Можно опросить статус службы сразу на множестве удаленных компьютеров, их имена нужно перечислить через запятую. Например, приведенная ниже команда получает состояние службы Spooler на удаленных компьютерах RM1 и RM2.
Get-Service spooler –ComputerName RM1,RM2
Вывести все свойства службы позволит командлет 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:
Для вывода служб с типом запуска Manual, выполните команду
Проверить, что в системе имеется указанная служба:
if (Get-Service «ServiceTest» -ErrorAction SilentlyContinue)
<
Write-host «ServiceTest exists»
>
Остановка, запуск, приостановка и перезапуск служб из PowerShell
Остановить службу можно с помощью командлета Stop-Service. Чтобы остановить службу печати, выполните команду:
Stop-Service -Name spooler
Командлет Stop-Service не выводит никаких данных после выполнения. Чтобы увидеть результат выполнения команды, используйте параметр -PassThru.
Обратите внимание, что не каждую службу можно остановить. Если есть зависимые службы, то получите ошибку
Для принудительной остановки используйте параметр –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
Командлет Suspend-Service может приостанавливать службы, допускающие временную приостановку и возобновление. Для получения сведений о возможности временной приостановки конкретной службы используйте командлет Get-Service со свойством «CanPauseAndContinue«.
Get-Service samss | Format-List name, canpauseandcontinue
Чтобы отобразить список всех служб, работа которых может быть приостановлена, введите команду:
Приостановим службу 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. Можно создавать, останавливать, запускать и возобновлять службы, менять их свойства. Большинство командлетов позволяют управлять службами на удаленных компьютерах.