Windows check service status

Get-Service: проверка состояния служб Windows в PowerShell

С помощью командлета Get-Service можно получить список всех установленных в системе служб, их состояние и тип запуска. Этот и другие командлеты для получения статуса и управления службами Windows впервые появился в версии Powershell 1.0. В этой статье мы разберем типовые примеры использования Get-Service для получения статуса служб на локальном или удаленных компьютерах, типе запуска служб и покажем как определять зависимости служб.

Получить список служб, установленных на локальном или удаленном компьютере можно с помощью командлета Get-Service. Команда Get-Service без параметров возвращает список всех служб на локальной системе.

Данная команда выведет список всех служб и их статус (запущена или остановлена) и отображаемое имя (Display Name).

Если вам нужно вывести только запушенные службы, воспользуемся такой командой:

Оператор конвейера (|) передает результаты командлету Where-Object, который отбирает только те службы, для которых параметр Status имеет значение Running. В том случае, если нужно вывести только остановленные службы, укажите значение Stopped.

Получить все свойства объекта службы можно с помощью командлета Get-Member.

Как вы видите, данный объект имеет тип (Typename) System.ServiceProcess.ServiceController. На скриншоте выведены все доступные свойства и методы объектов служб в системе (большинство из них не используются при отображении по умолчанию).

Чтобы вывести определенные свойства службы, нужно воспользоваться возможностями выбора свойств объектов с помощью командлета Select. Например, нам нужно вывести имя, статус и доступные возможности службы Windows Update:

get-service wuauserv | select Displayname,Status,ServiceName,Can*

DisplayName : Windows Update
Status : Stopped
CanPauseAndContinue : False
CanShutdown : False
CanStop : False

К примеру, чтобы получить тип запуска служб Windows, выполните команду (работает в PowerShel 5.1):

Get-Service | select -property name,starttype

Можно отфильтровать полученный список по имени службы, используя звездочку как подстановочный знак:

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

get-service s* | sort-object status -Descending

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

if (Get-Service «ServiceTest» -ErrorAction SilentlyContinue)
<
Write-host «ServiceTest exists»
>

Командлет Get-Service можно использовать для получения статуса служб не только на локальном, но и удаленных компьютерах. Для этого нужно использовать аргумент –Computername. Подключение к удаленным компьютерам осуществляется не через PowerShell Remoting (WinRM), а через службу Service Manager (по аналогии с командой sc.ex).

get-service wuauserv -ComputerName remotePC1

Если вы используете PowerShell v3 или выше, то можно опросить статус службы сразу на множестве удаленных компьютерах, их имена нужно перечислить через запятую.

get-service spooler -ComputerName remotePC1,remotePC2, remotePC3| format-table Name,Status,Machinename –autosize

Командлет format-table используется в данном примере для получения более удобного табличного представления состояния служб.

Командлет Get-Service имеет еще два параметра, которые удобно использовать при администрировании служб. Параметр DependentServices получает службы, которые зависят от данной службы. Параметр RequiredServices получает службы, от которых зависит данная служба.

Читайте также:  Как перезагрузить операционную систему windows

Приведенная ниже команда выводит список служб, требуемых службе LanmanWorkstation для запуска.

Get-Service -Name LanmanWorkstation –RequiredServices

Status Name DisplayName
—— —- ————
Running NSI Network Store Interface Service
Running MRxSmb20 SMB 2.0 MiniRedirector
Running Bowser Browser Support Driver

Следующая команда выводит зависимые службы (подробнее о настройке зависимостей служб в Windows), которым требуется служба LanmanWorkstation.

Get-Service -Name LanmanWorkstation -DependentServices

SERVICE_STATUS structure (winsvc.h)

Contains status information for a service. The ControlService, EnumDependentServices, EnumServicesStatus, and QueryServiceStatus functions use this structure. A service uses this structure in the SetServiceStatus function to report its current status to the service control manager.

Syntax

Members

The type of service. This member can be one of the following values.

Value Meaning
SERVICE_FILE_SYSTEM_DRIVER 0x00000002 The service is a file system driver.
SERVICE_KERNEL_DRIVER 0x00000001 The service is a device driver.
SERVICE_WIN32_OWN_PROCESS 0x00000010 The service runs in its own process.
SERVICE_WIN32_SHARE_PROCESS 0x00000020 The service shares a process with other services.
SERVICE_USER_OWN_PROCESS 0x00000050 The service runs in its own process under the logged-on user account.
SERVICE_USER_SHARE_PROCESS 0x00000060 The service shares a process with one or more other services that run under the logged-on user account.

В

If the service type is either SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS, and the service is running in the context of the LocalSystem account, the following type may also be specified.

Value Meaning
SERVICE_INTERACTIVE_PROCESS 0x00000100 The service can interact with the desktop.

The current state of the service. This member can be one of the following values.

Value Meaning
SERVICE_CONTINUE_PENDING 0x00000005 The service continue is pending.
SERVICE_PAUSE_PENDING 0x00000006 The service pause is pending.
SERVICE_PAUSED 0x00000007 The service is paused.
SERVICE_RUNNING 0x00000004 The service is running.
SERVICE_START_PENDING 0x00000002 The service is starting.
SERVICE_STOP_PENDING 0x00000003 The service is stopping.
SERVICE_STOPPED 0x00000001 The service is not running.

The control codes the service accepts and processes in its handler function (see Handler and HandlerEx). A user interface process can control a service by specifying a control command in the ControlService or ControlServiceEx function. By default, all services accept the SERVICE_CONTROL_INTERROGATE value.

To accept the SERVICE_CONTROL_DEVICEEVENT value, the service must register to receive device events by using the RegisterDeviceNotification function.

The following are the control codes.

Control code Meaning
SERVICE_ACCEPT_NETBINDCHANGE 0x00000010 The service is a network component that can accept changes in its binding without being stopped and restarted.

This control code allows the service to receive SERVICE_CONTROL_NETBINDADD, SERVICE_CONTROL_NETBINDREMOVE, SERVICE_CONTROL_NETBINDENABLE, and SERVICE_CONTROL_NETBINDDISABLE notifications.

SERVICE_ACCEPT_PARAMCHANGE 0x00000008 The service can reread its startup parameters without being stopped and restarted.

This control code allows the service to receive SERVICE_CONTROL_PARAMCHANGE notifications.

SERVICE_ACCEPT_PAUSE_CONTINUE 0x00000002 The service can be paused and continued.

This control code allows the service to receive SERVICE_CONTROL_PAUSE and SERVICE_CONTROL_CONTINUE notifications.

SERVICE_ACCEPT_PRESHUTDOWN 0x00000100 The service can perform preshutdown tasks.

This control code enables the service to receive SERVICE_CONTROL_PRESHUTDOWN notifications. Note that ControlService and ControlServiceEx cannot send this notification; only the system can send it.

Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported.

SERVICE_ACCEPT_SHUTDOWN 0x00000004 The service is notified when system shutdown occurs.

This control code allows the service to receive SERVICE_CONTROL_SHUTDOWN notifications. Note that ControlService and ControlServiceEx cannot send this notification; only the system can send it.

SERVICE_ACCEPT_STOP 0x00000001 The service can be stopped.

This control code allows the service to receive SERVICE_CONTROL_STOP notifications.

This member can also contain the following extended control codes, which are supported only by HandlerEx. (Note that these control codes cannot be sent by ControlService or ControlServiceEx.)

Control code Meaning
SERVICE_ACCEPT_HARDWAREPROFILECHANGE 0x00000020 The service is notified when the computer’s hardware profile has changed. This enables the system to send SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
SERVICE_ACCEPT_POWEREVENT 0x00000040 The service is notified when the computer’s power status has changed. This enables the system to send SERVICE_CONTROL_POWEREVENT notifications to the service.
SERVICE_ACCEPT_SESSIONCHANGE 0x00000080 The service is notified when the computer’s session status has changed. This enables the system to send SERVICE_CONTROL_SESSIONCHANGE notifications to the service.
SERVICE_ACCEPT_TIMECHANGE 0x00000200 The service is notified when the system time has changed. This enables the system to send SERVICE_CONTROL_TIMECHANGE notifications to the service.

Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

SERVICE_ACCEPT_TRIGGEREVENT 0x00000400 The service is notified when an event for which the service has registered occurs. This enables the system to send SERVICE_CONTROL_TRIGGEREVENT notifications to the service.

Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

SERVICE_ACCEPT_USERMODEREBOOT 0x00000800 The services is notified when the user initiates a reboot.

Windows ServerВ 2008В R2, WindowsВ 7, Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

The error code the service uses to report an error that occurs when it is starting or stopping. To return an error code specific to the service, the service must set this value to ERROR_SERVICE_SPECIFIC_ERROR to indicate that the dwServiceSpecificExitCode member contains the error code. The service should set this value to NO_ERROR when it is running and on normal termination.

A service-specific error code that the service returns when an error occurs while the service is starting or stopping. This value is ignored unless the dwWin32ExitCode member is set to ERROR_SERVICE_SPECIFIC_ERROR.

The check-point value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up. The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending.

The estimated time required for a pending start, stop, pause, or continue operation, in milliseconds. Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function with either an incremented dwCheckPoint value or a change in dwCurrentState. If the amount of time specified by dwWaitHint passes, and dwCheckPoint has not been incremented or dwCurrentState has not changed, the service control manager or service control program can assume that an error has occurred and the service should be stopped. However, if the service shares a process with other services, the service control manager cannot terminate the service application because it would have to terminate the other services sharing the process as well.

C# check windows Service status

I’m using the following code to check my windows service status:

in the service location H’m putting the server name which my service reside on. on my test environment, I have the service and portal (IIS) where I check my service on the same server and it works fine, but on my production environment, The service is on a different server than my portal IIS.

and my code is unable to check the status. I’m sure it is a permission issue, but I tried so many this to make it work but no use.

my question is: what «type of permission» to be given to what «user» or «machine name»? please help.

2 Answers 2

Does your IIS portal impersonate? It seems it does. As such you are falling into Kerberos constrained delegation (‘two-hop’). You cannot ‘fix’ this. You have to ask a domain administrator to enable and configure constrained delegation for your IIS application.

An alternative is not to impersonate in your IIS. In this case you need grant appropriate permissions to your portal app pool. The required permission in SC_MANAGER_CONNECT . Read more at KB179249: Access to the Service Control Manager. Obviously the app-pool must be a domain account and the IIS and target service host machine should be in the same domain, or in domains that have a trust relationship.

Thanks to all anyway, I have used another way through WMI and it worked:

Not the answer you’re looking for? Browse other questions tagged windows-services or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Читайте также:  Маски для веб камеры для windows
Оцените статью