- Get-Service
- Syntax
- Description
- Examples
- Example 1: Get all services on the computer
- Example 2: Get services that begin with a search string
- Example 3: Display services that include a search string
- Example 4: Get services that begin with a search string and an exclusion
- Example 5: Display services that are currently active
- Example 6: List the services on the computer that have dependent services
- Example 7: Sort services by property value
- Example 8: Get the dependent services of a service
- Example 9: Get a service through the pipeline operator
- Parameters
- Inputs
- Outputs
- Notes
- How To Check Windows Service Status With Get-Service Command In Powershell
- List All Services
- List All Service On Remote Computer or System
- List Services with Specified Name
- List Only Currently Running Services
- List Service with Dependent Service
- List Sorted By Status (Stopped/Running)
- Управляем службами Windows с помощью PowerShell
- ПОЛУЧАЕМ СТАТУС СЛУЖБЫ
- ПОЛУЧАЕМ СТАТУС СЛУЖБЫ НА УДАЛЕННЫХ КОМПЬЮТЕРАХ
- ОСУЩЕСТВЛЯЕМ ФИЛЬТРАЦИЮ (ИСПОЛЬЗУЯ WHERE-OBJECT)
- ЗАВИСИМЫЕ СЛУЖБЫ
Get-Service
Gets the services on the computer.
Syntax
Description
The Get-Service cmdlet gets objects that represent the services on a computer, including running and stopped services. By default, when Get-Service is run without parameters, all the local computer’s services are returned.
You can direct this cmdlet to get only particular services by specifying the service name or the display name of the services, or you can pipe service objects to this cmdlet.
Examples
Example 1: Get all services on the computer
This example gets all of the services on the computer. It behaves as though you typed Get-Service * . The default display shows the status, service name, and display name of each service.
Example 2: Get services that begin with a search string
This example retrieves services with service names that begin with WMI (Windows Management Instrumentation).
Example 3: Display services that include a search string
This example displays services with a display name that includes the word network. Searching the display name finds network-related services even when the service name doesn’t include Net, such as xmlprov, the Network Provisioning Service.
Example 4: Get services that begin with a search string and an exclusion
This example only gets the services with service names that begin with win, except for the WinRM service.
Example 5: Display services that are currently active
This example displays only the services with a status of Running.
Get-Service gets all the services on the computer and sends the objects down the pipeline. The Where-Object cmdlet, selects only the services with a Status property that equals Running.
Status is only one property of service objects. To see all of the properties, type Get-Service | Get-Member .
Example 6: List the services on the computer that have dependent services
This example gets services that have dependent services.
The Get-Service cmdlet gets all the services on the computer and sends the objects down the pipeline. The Where-Object cmdlet selects the services whose DependentServices property isn’t null.
The results are sent down the pipeline to the Format-List cmdlet. The Property parameter displays the name of the service, the name of the dependent services, and a calculated property that displays the number of dependent services for each service.
Example 7: Sort services by property value
This example shows that when you sort services in ascending order by the value of their Status property, stopped services appear before running services. The reason is because the value of Status is an enumeration, in which Stopped has a value of 1, and Running has a value of 4. For more information, see ServiceControllerStatus.
To list running services first, use the Descending parameter of the Sort-Object cmdlet.
Example 8: Get the dependent services of a service
This example gets the services that the WinRM service requires. The value of the service’s ServicesDependedOn property is returned.
Example 9: Get a service through the pipeline operator
This example gets the WinRM service on the local computer. The service name string, enclosed in quotation marks, is sent down the pipeline to Get-Service .
Parameters
Indicates that this cmdlet gets only the services that depend upon the specified service.
Type: | SwitchParameter |
Aliases: | DS |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, the display names of services to be retrieved. Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies, as a string array, a service or services that this cmdlet excludes from the operation. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as s* . Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies, as a string array, a service or services that this cmdlet includes in the operation. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as s* . Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies ServiceController objects representing the services to be retrieved. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can pipe a service object to this cmdlet.
Type: | ServiceController [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the service names of services to be retrieved. Wildcards are permitted.
Type: | String [ ] |
Aliases: | ServiceName |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Indicates that this cmdlet gets only the services that this service requires. This parameter gets the value of the ServicesDependedOn property of the service.
Type: | SwitchParameter |
Aliases: | SDO, ServicesDependedOn |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Inputs
System.ServiceProcess.ServiceController, System.String
You can pipe a service object or a service name to this cmdlet.
Outputs
This cmdlet returns objects that represent the services on the computer.
Notes
This cmdlet is only available on Windows platforms.
Beginning in PowerShell 6.0, the following properties are added to the ServiceController objects: UserName, Description, DelayedAutoStart, BinaryPathName, and StartupType .
You can also refer to Get-Service by its built-in alias, gsv . For more information, see about_Aliases.
This cmdlet can display services only when the current user has permission to see them. If this cmdlet does not display services, you might not have permission to see them.
To find the service name and display name of each service on your system, type Get-Service . The service names appear in the Name column, and the display names appear in the DisplayName column.
When you sort in ascending order by the Status property’s value, Stopped services appear before Running services. The service’s Status property is an enumerated value and the status names represent integer values. The sort order is based on the integer value, not the name. Stopped appears before because Running because Stopped has a value of 1, and Running has a value of 4. For more information, see ServiceControllerStatus.
How To Check Windows Service Status With Get-Service Command In Powershell
Service are one of the most important part of the operating systems. There are different tools and commands to list these services. Powershell provides Get-Service commandlet in order to list these services and filter them acording to the provided filter.
List All Services
We will start with a simple use case where we will list all services without providing an options to the Get-Service command. This will list currently existing service with running or stopped status.
List All Services
As we can see from screenshot services are ordered by name by default. Following information is provided by default about listed services.
- Status will display if the service is Running or Stopped
- Name will display the real and short name of the service which is used by commands.
- Display Name will show extended and informative name of the service which is more human friendly.
List All Service On Remote Computer or System
As Microsoft provided remote access and management of the remote systems with powreshell we can use Get-Service command in order to list services on the remote systems. We will provide the -computername of the remote system. This can a DNS name which can be resolved or a IP address we can access.
List All Service On Remote Computer or System
List Services with Specified Name
Windows operating systems has a lot of services which will fill the terminal easily. Or we may need to list specific service name by providing its name of some part of its name. We will just provide the name after Get-Service command. We can also use * glob where only some part of the service name will be specified. In this example we will try to list WinDefend service by providing WinDef* as service name.
List Services with Specified Name
List Only Currently Running Services
There is two main service status in Windows. Running or Stopped . We may need to list services according to their status. We can use object parameter Status like below which will list only running services.
List Only Currently Running Services
List Service with Dependent Service
Services are important and may be linked and dependent to each other. Before stopping them we may need to list dependent services of the given service. We can use -RequiredServices options in order to list service dependencies.
List Service with Dependent Service
List Sorted By Status (Stopped/Running)
We may need to check service list according to their Running and Stopped status. We can sort them by using Sort-Object like below.
Управляем службами Windows с помощью PowerShell
Начинаем серию переводов, посвященную управлению службами Windows с помощью PowerShell 2.0 и 3.0.
В данном посте будут рассмотрены следующие вопросы управления службами Windows:
- Получаем статус службы на локальном компьютере
- Получаем статус службы на удаленном компьютере
- Осуществляем фильтрацию служб (например, остановленные службы)
- Зависимые службы
Обозначим начальные условия: Вы работаете под Windows 7 и выше и у Вас имеются права администратора. Все команды рекомендуются выполнять в лабораторной или виртуальной среде, перед тем, как применять в “полевых условиях”.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ
Давайте начнем с того, что просто получим статус всех служб, запущенных на локальном компьютере. Используем для этого командлет Get-Service.
PowerShell, как правило, не чувствителен к регистру. Вывод приведен на скриншоте ниже.
Каждая строка представляет собой объект службы (service object).Каждый сервисный объект, как правило, имеет свои свойства. Вы можете открыть их, просто передав эти объекты в другую команду, Get-Member.
Результаты приведены на скриншоте ниже.
Параметр Typename сверху говорит о том, что за объект перед нами; в данном случае это System.ServiceProcess.ServiceController. На скриншоте также обведены свойства объекта. Это атрибуты, которые описывают этот тип объекта. Хотя большинство из них не используются при отображении по умолчанию, вы можете использовать их, если вы их знаете.
Например, нам интересно посмотреть информацию только о Windows Update. Через Get-Service получим информацию только о некоторых ее свойствах.
Как я узнал, что могу напечатать имя службы? Посмотрел с помощью Get-Service.
PS C:\> help get-service
Вы можете получить полную справочную информацию, напечатав:
Информацию о службе можно получить по ее имени или даже начальным буквам имени.
Или если вам удобнее работать с отображаемыми именами, используйте параметр –Displayname.
Я должен использовать имя параметра, чтобы PowerShell воспринимал значения в качестве отображаемого имени, а не фактического имени службы. Команда будет выглядеть так:
Параметр –Name можно не печатать.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ НА УДАЛЕННЫХ КОМПЬЮТЕРАХ
До этого нас интересовало получение информации о статусе служб на локальном компьютере. Однако управление службами осуществляется на удаленных компьютерах. Если посмотреть справку по Get-Service, то можно увидеть наличие у этого командлета параметра –Computername. В данном случае подключение к удаленным компьютерам осуществляется без включения функции удаленного управления PowerShell. Если вы можете управлять службами, используя инструменты командной строки (sc.exe или консоль управления Service Manager), вы можете использовать PowerShell. Давайте взглянем на пример:
Любая команда, которую я демонстрировал, можно использовать для передачи удаленному компьютеру. Даже нескольким компьютерам, если у вас есть соответствующие права на удаленном компьютере. Если вы используете PowerShell v3, то можно легко выбрать одну службу на множестве компьютеров.
Для наглядности представления отформатируем вывод.
Тот же самый результат, но в PowerShell v2.
ОСУЩЕСТВЛЯЕМ ФИЛЬТРАЦИЮ (ИСПОЛЬЗУЯ WHERE-OBJECT)
Фильтрация служб осуществляется с помощью командлета Where-Object (where – сокращение для командлета). Все, что нам нужно от PowerShell в этом случае, так это получить только те службы, у которых статус равен “stopped”.
PowerShell получает информацию обо всех службах и передает их (с помощью “|”) в следующую команду, которая осуществляет просмотр каждого объекта. Если свойство статуса объекта равно “stopped”, она остается в конвейере (pipeline), в противном случае она из него исключается. В конце выражение PowerShell отображает те объекты, которые остались в конвейере.
Результаты приведены ниже.
Теперь давайте попробуем найти одну службу на нескольких машинах. Вывод отформатируем в таблицу.
Мы даже можем комбинировать запрос отдельных служб с их фильтрацией.
Эта команда находит все службы на компьютере CHI-DC03, которые начинаются с ‘WIN’, но отображает только те, которые запущены.
Также можно сгруппировать объекты по свойству статуса (status property).
Переменная $dc03 является объектом GroupInfo.
Свойство Group представляет собой коллекцию связанных служб.
Написанное выше проще понять, если взглянуть на скриншот.
Что касается меня, то я бы предпочел использовать хеш-таблицу.
Теперь каждое имя представляет собой свойство в хеш-таблице. Если у вас имеется опыт работы с PoweShell, вы, возможно, подумываете сделать сделующее:
Однако ничего не произойдет. Потому что свойство Status является просто перечислением (enumeration) для [System.ServiceProcess.ServiceControllerStatus] .NET клас и такие свойства, как Running и Stopped представляют собой целые числа. PowerShell осуществляет конвертацию, чтобы представить в более наглядной форме.
В чем суть параметра –AsString, на мой взгляд, достаточно очевидно. Теперь работать с хеш-таблицей стало проще.
Следующей задачей на повестке дня является проверка зависимостей сервера (server dependencies).
Требуемые службы
PowerShell позволяет просто получить статус всех служб, которые требуется для данной службы, даже на удаленном компьютере.
Параметр –RequiredServices передаст объект в конвейер для каждой требуемой службы. Вы можете даже пойти дальше и проверить требуемые службы для работы данной службы.
Параметр –Computername командлета Get-Service возьмет вывод, но только для тех объектов, у которых есть объект свойство Computername – именно поэтому я использую хеш-таблицу с Select-Object. Как мы видим проблем со службой DNS на компьютере CHI-DC03 нет.
ЗАВИСИМЫЕ СЛУЖБЫ
Мы можем сделать то же самое с зависимыми службами. Если таковых не имеется, в конвейер ничего передано не будет.
Требуемые и зависимые службы также являются частью каждого объекта службы.
А пока Вы можете получить все зависимости для всех служб, следующая команда
Это не даст вам особо полезную информацию, поэтому я рекомендую осуществлять запрос по конкретным службам. Команда работает гораздо лучше PowerShell v3.
Результаты видны на скриншоте ниже.
Чтобы получить подобные результаты в PowerShell v2, вам придется передать имена компьютеров (computernames) в Get-Service.
В следующей статье будет рассмотрен запуск, остановка и перезапуск служб.
Конец перевода.