В 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. Можно создавать, останавливать, запускать и возобновлять службы, менять их свойства. Большинство командлетов позволяют управлять службами на удаленных компьютерах.
The «PowerShell services list» allows users to view the current status of all installed services on a Windows system by using a simple command. Here’s a code snippet to retrieve this information:
Get-Service
What Are Windows Services?
Windows Services are specialized applications that run in the background of a Windows operating system to perform essential tasks without user intervention. These services are managed through the Windows Services Control Manager and can be set to start automatically, manually, or be disabled entirely. They serve various functions, including managing hardware components, running web servers, and processing background tasks.
Common Windows Services include:
- Print Spooler: Manages print jobs.
- Windows Update: Ensures the system receives updates and patches regularly.
- SQL Server: Manages SQL databases, often used in enterprise environments.
Understanding these services can help you maintain system efficiency and troubleshoot problems effectively.
Mastering PowerShell Search History: A Quick Guide
Introduction to PowerShell Commands
PowerShell is a task automation framework from Microsoft, consisting of a command-line shell and associated scripting language. It is particularly powerful for Windows system administrators, allowing them to automate routine tasks and manage configurations.
The command-line nature and scriptability of PowerShell make it an excellent tool for querying, modifying, and managing Windows Services.
PowerShell Operators List: A Quick Reference Guide
Understanding the Get-Service Cmdlet
The `Get-Service` cmdlet in PowerShell is used to retrieve the status of services on your system. It provides a straightforward way to access information regarding services, such as their names, display names, and current statuses (Running, Stopped, etc.).
The basic syntax of `Get-Service` is:
Get-Service [-Name <String[]>] [-DisplayName <String[]>] [-DependentServices] [-RequiredServices] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-InputObject <ServiceController[]>] [-PassThru] [-Exclude <String[]>] [-Credential <PSCredential>] [-ThrottleLimit <Int32>] [-AsJob] [-Session <PSSession>] [-NoProfile] [<CommonParameters>]
Basic Usage of Get-Service
You can use the `Get-Service` command without any parameters to list all services on the system. This is incredibly useful for getting an overview of all running applications.
Get-Service
When executed, this command outputs a list of all services along with their respective statuses and display names, helping you quickly identify what services are installed.
Filtering Services with Get-Service
Listing Specific Services
If you wish to check the status of a specific service, you can do so by utilizing the `-Name` parameter. For instance, if you’re looking for the status of the Print Spooler service, the command would be:
Get-Service -Name "Spooler"
This command provides focused information only about the Print Spooler service, allowing for quick checks without the clutter of unrelated services.
Filtering Services Based on Status
In many cases, you may want to filter the services by their running status—either looking for those that are running or stopped. The following example shows how to list only the running services:
Get-Service | Where-Object { $_.Status -eq 'Running' }
Here, `Where-Object` is used to filter the results returned by `Get-Service`, making it easy to focus on services that you may want to manage immediately.
Mastering PowerShell Write-Host for Vibrant Outputs
Customizing Your Services List
Selecting and Formatting Output
Customizing output makes it easier to read and analyze the information you retrieve. You can select specific properties, such as Name, DisplayName, and Status, by using the `Select-Object` cmdlet:
Get-Service | Select-Object Name, DisplayName, Status
This command trims down the output to only the relevant information about the services, making it more digestible for further analysis or reporting.
Sorting Services
If you want to present your services in a more structured way, you might want to sort them alphabetically by their display names. The following command sorts the services accordingly:
Get-Service | Sort-Object DisplayName
Utilizing `Sort-Object` can drastically improve the readability of the services list, allowing you to quickly locate a specific service.
Mastering PowerShell SecureString: Your Essential Guide
Using List Windows Services PowerShell
Listing Windows Services with Additional Filters
To refine your services list even further, you can combine multiple commands and filters. For instance, if you want to display only those services that are stopped and sort them alphabetically:
Get-Service | Where-Object { $_.Status -eq 'Stopped' } | Sort-Object DisplayName
This command is powerful for both administrative tasks and system audits, as it highlights services that may need attention, such as those that are not running when they should be.
Exporting Services List to a File
PowerShell enables you to export your services list for reporting or documentation purposes. You can easily export the findings to a CSV file using the following command:
Get-Service | Export-Csv -Path "C:\services_list.csv" -NoTypeInformation
This command saves your filtered or sorted services list to a CSV file located at `C:\`. This is particularly useful for sharing with team members or for further analysis in Excel or similar programs.
Mastering The PowerShell Semicolon: A Quick Guide
Additional Cmdlets for Managing Services
Start-Service and Stop-Service Cmdlets
While retrieving information about services is vital, managing them is equally important. The `Start-Service` and `Stop-Service` cmdlets allow you to control the services directly.
To start a service, you can execute:
Start-Service -Name "Spooler"
Conversely, if you need to stop it, just replace the command like so:
Stop-Service -Name "Spooler"
These commands are instrumental in ensuring that vital services are running smoothly and can assist in troubleshooting by allowing you to restart problematic services.
Restarting Services
Sometimes, you may need to restart a service to apply changes or resolve issues. PowerShell makes this process straightforward:
Restart-Service -Name "Spooler"
Using `Restart-Service` not only halts the service but also reinitializes it, which can often resolve temporary issues without requiring a system reboot.
Mastering PowerShell GPResult for Insightful Reporting
Conclusion
In summary, mastering the PowerShell Services List commands opens the door to effective Windows administration and service management. From listing services to customizing output and actively managing them, PowerShell provides an extensive set of tools tailored for system administrators.
For anyone interested in learning more about PowerShell commands and their applications, consider enrolling in a dedicated training program. This foundational knowledge will prove invaluable in maintaining and managing your Windows environment effectively.
Mastering PowerShell Register-ScheduledTask Made Easy
Additional Resources
For further exploration, consider reviewing the official [Microsoft PowerShell documentation](https://docs.microsoft.com/powershell/) and community resources that can deepen your understanding of command-line automation.
Windows services are Windows executables that run in the background to support the working of some Windows processes. These services can be started, stopped, restarted, suspended, resumed, or even removed.
Note: Some services are vital to the workings of the OS system, and removing or stopping them may cause the OS to restart or even crash.
The list of all Windows services can be fetched in the Windows PowerShell using the Get-Service cmdlet. The problem with the command is that it may generate a long list, so what you are looking for might be hard to find.
This article will discuss some examples of working with Get-Service efficiently.
Example 1: Listing all Windows Services
You can get the list of all Windows services by running the command.
The command outputs Windows services with three properties:
- Status – shows the status of the service – running or stopped,
- Name – the name of the service,
- DisplayName – a more human-readable description of what the service is all about.
Example 2: Sort the Get-Service Output by a Given Field
Note that the Get-Service output is, by default, sorted by Name (see Example 1). You can sort the output with any of the other fields. For example,
Get—Service | Sort—Object —Property DisplayName —Descending |
Example 3: Get Services with Specific Names
To get the specific services, provide the names of the services you want to fetch, separated by a comma. Note that this only works with Name and DisplayName properties.
Get—Service —Name winmgmt,sshd,ssh—agent |
Example 4: Filtering the Get-Service List Using Wildcards
You can also use wildcards to filter the outputs based on Name or DisplayName. For example,
Get—Service —DisplayName WLAN*, P*s, «*Remote Desktop*» |
* wildcard character matches zero or more characters. That means WLAN* matches services starting with the string “WLAN”, “*Remote Desktop*” matches services with the substring “Remote Desktop” in their DisplayName, and P*s matches services that start with P and ends with s in their DisplayName.
You can read more about PowerShell wildcards here.
Example 5: Filter Services Based on their Status
We cannot filter the services directly based on Status as we did in Examples 3 and 4. But we can still filter by piping output into the Where-Object cmdlet and issuing the condition, as shown below.
Get—Service | Where—Object {$_.Status —eq «Stopped»} |
The command above will fetch all services whose Status is equal (-eq) to “Stopped”.
Example 6: Selecting other Properties in Get-Service
Get-Command does not come with only the three properties we have discussed. There is More. You can see all methods and objects of Get-Service by running the command
Apart from Name, DisplayName, and Status, the other objects include Description, StartupType, etc.
You can then pick the properties you need from the available ones using the Select-Object cmdlet. For example, the following command shows the Name, Description of the service, and properties starting with “Start”.
Get—Service | Select—Object Name, Description, Start* |
Example 7: Getting all Services that can be Paused Without OS Restarting
As said earlier, some services are critical to the functionality of the OS. Any attempt to pause such services may cause the OS to restart. You can check for those vital services using the command:
Get—Service | Where—Object {$_.CanPauseAndContinue —EQ «false»} |
If you want to see the services that can be suspended and resumed without a problem, you can set the CanPauseAndContinue to “true”.
Example 8: Excluding/Including Some Services from/to the List
The Get-Service commands have the -Include and -Exclude options that allow us to filter our outputs even more.
These two options work for the Name parameter only and accept wildcards. Here is an example.
Get—Service —Name «vmi*» —Exclude vmicshutdown, vmicrdv |
The command above gets all services whose Name starts with “vmi” but excludes vmicshutdown and vmicrdv services. The -Include option works similarly but does the opposite.
After going through Examples 1 through 8, you should be able to get the Get-Service list containing the services you need. The next is to take care of the output.
Example 9: Output to a Grid View
The default behavior is that you will see the output of Get-Service on the PowerShell console. We can send the output into grid view instead of using the Out-GridView cmdlet, as shown below.
Get—Service —Name «vmi*» | Out—GridView |
After running the command above, a new grid-like window will appear and show the result of the Get-Service command.
Example 10: Write the Output to a File
Alternatively, you can send the results to a file using the Out-File command, as shown below.
Get—Service | Where—Object {$_.Status —eq «Running»} | Out—File «. \running_services.txt» |
The command will send the list of all running services into the running_services.txt.
Conclusion
This guide explains how to use Get-Service to list Windows Services on PowerShell. After going through the 10 examples covered in this article, you should be able to filter your services list and control the output based on your needs.
The running applications you see on your screen are a fraction of what is happening in Windows. From managing device drivers to ensuring security, a bunch of background processes maintain a functioning Windows PC.
For any system administrator overseeing multiple computers, it is important to be able to view the status of these critical services. The Task Manager approach is too slow for this, and you cannot automate it with a script.
The solution? Command-line tools. Using the Command Prompt or PowerShell, you can quickly get a read on the operational Microsoft services running on a system, helping you diagnose any issues swiftly.
Listing Windows Services In the Command Prompt
While not as flexible or powerful as Windows PowerShell, the Command Prompt is still an excellent tool for system administrators. You can use the queryex command to get the status of both active and disabled services and then use the taskkill command to end pesky processes.
- To use the queryex command, run Command Prompt as an Administrator. You can find the app by searching cmd in the start menu.
- There are many ways of using the sc queryex command. Type and State are the two most commonly used parameters. For example, enter the following command to view all Windows processes:
sc queryex type=service state=all
- The default view can be a bit overwhelming. You can display just the names of processes to make the list easier to parse:
sc queryex type=service state=all | find /i “SERVICE_NAME:”
- By default, the command lists all active processes. To look for inactive ones, modify the state parameter:
sc queryex type=service state=inactive
- You can also query the status of a specific process by its name. This is incredibly useful for system administrators, as they can set up batch files to check many processes at once. Here’s an example:
sc query DeviceInstall
Listing Windows Services in PowerShell
PowerShell is meant to be a dedicated command-line shell for modern Windows. As such, it provides access to pretty much every operating system component through commands, and Windows services are no exception.
PowerShell’s advantage is that you can automate it easily. All PowerShell commands can be compiled into complex scripts, allowing you to set up system administration tasks on multiple PCs without hassle.
- Start by opening PowerShell. You can search for it in the Start Menu; just make sure to run an elevated instance (i.e., as an Administrator).
- The simplest command for listing Windows services on PowerShell is Get-Service. It shows all services on your computer, along with their status and names. The only problem is that the list of services can be pretty long.
- When using Get-Service, it is a better idea to export the list to a text file. You can do this using pipes, like this:
Get-Service | Out-File “C:\logs\All_Services.txt”
- To look up the status of a specific service, follow the Get-Service command with the name of the service. You can request the status of multiple processes by separating their names with commas.
Get-Service CryptSvc, COMSysApp
- Pipes can also be used to combine the Get-Service cmdlet with the Where-Object function and filter the results by Status. The following command illustrates this by getting all Running services:
Get-Service | Where-Object {$_.Status -EQ “Running”}
Checking Service Dependencies
Any complex process is split into multiple interdependent services. This is why simply getting the status of a particular service is often not enough. You also need to check the status of the services that service is dependent on.
- To view the services required by a particular service, use the -RequiredServices flag with the Get-Service cmdlet. Here’s an example:
Get-Service -Name CryptSvc –RequiredServices
- Similarly, to get a list of services that depend on a specific service, take advantage of the -DependentServices flag.
Get-Service -Name CryptSvc -DependentServices
These two flags are crucial in writing scripts to automatically start or stop Windows services, as they give you a way to keep track of all the services connected with the affected service.
Listing Windows Services On Remote Computers
The PowerShell method is not limited to local computers. You can use the Get-Service cmdlet with the same syntax described above to query the processes of remote PCs as well. Just append the -ComputerName flag at the end to specify which remote computer to retrieve information from.
Here’s an example:
get-service CryptSvc -ComputerName Workstation7
Managing Windows Services in PowerShell
Getting the status of services isn’t the only thing you can do in Windows PowerShell. As a full-fledged scripting environment, it provides script alternatives to all GUI options.
Powershell cmdlets can stop, start, restart, or even modify services. Paired with automated Get-Service commands, PowerShell scripts can be written to fully automate everyday system management tasks.
- In addition to querying the status of services, you can also use PowerShell to manage them. Starting or stopping services can be done with a single command, requiring only the name of the service. For example, this is how you can stop a service:
Stop-Service -Name Spooler
- Starting a service goes similarly:
Start-Service -Name Spooler
- If a service isn’t working correctly, you can also choose to restart it:
Restart-Service -Name Spooler
- There is also the Set-Service cmdlet that can be used to change the properties of a service. Here we disable the automatic startup of the Print Spooler service:
Set-Service ‘Spooler’ -StartupType Disabled
What Is the Best Way to List Windows Services?
Whether you are running Windows 10 or a Windows Server, being able to view a list of all Windows services can be handy. You can diagnose issues with critical system functions or stop unnecessary Microsoft services to improve performance.
For this purpose, PowerShell is the best option. While you can obtain a service list in Command Prompt, the additional functionality provided by PowerShell is more useful.
You can use PowerShell cmdlets to get the service status of Windows processes, filtering them by their status or other parameters. It is also easy to determine dependent services and start or stop them as required.
Related Posts
- How to Fix a “This file does not have an app associated with it” Error on Windows
- How to Add OneDrive to Windows File Explorer
- How to Fix an Update Error 0x800705b4 on Windows
- How to Resolve “A JavaScript error occured in the main process” Error on Windows
- How to Fix the Network Discovery Is Turned Off Error on Windows
Начинаем серию переводов, посвященную управлению службами Windows с помощью PowerShell 2.0 и 3.0.
В данном посте будут рассмотрены следующие вопросы управления службами Windows:
- Получаем статус службы на локальном компьютере
- Получаем статус службы на удаленном компьютере
- Осуществляем фильтрацию служб (например, остановленные службы)
- Зависимые службы
Обозначим начальные условия: Вы работаете под Windows 7 и выше и у Вас имеются права администратора. Все команды рекомендуются выполнять в лабораторной или виртуальной среде, перед тем, как применять в “полевых условиях”.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ
Давайте начнем с того, что просто получим статус всех служб, запущенных на локальном компьютере. Используем для этого командлет Get-Service.
PS C:\> get-service
PowerShell, как правило, не чувствителен к регистру. Вывод приведен на скриншоте ниже.
Каждая строка представляет собой объект службы (service object).Каждый сервисный объект, как правило, имеет свои свойства. Вы можете открыть их, просто передав эти объекты в другую команду, Get-Member.
PS C:\> get-service | get-member
Результаты приведены на скриншоте ниже.
Параметр Typename сверху говорит о том, что за объект перед нами; в данном случае это System.ServiceProcess.ServiceController. На скриншоте также обведены свойства объекта. Это атрибуты, которые описывают этот тип объекта. Хотя большинство из них не используются при отображении по умолчанию, вы можете использовать их, если вы их знаете.
Например, нам интересно посмотреть информацию только о Windows Update. Через Get-Service получим информацию только о некоторых ее свойствах.
PS C:\> get-service wuauserv | select Displayname,Status,Can*
DisplayName : Windows Update
Status : Stopped
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
Как я узнал, что могу напечатать имя службы? Посмотрел с помощью Get-Service.
PS C:\> help get-service
Вы можете получить полную справочную информацию, напечатав:
PS C:\> help get-service –full
Информацию о службе можно получить по ее имени или даже начальным буквам имени.
PS C:\> get-service wi*
Status Name DisplayName
------ ---- -----------
Stopped WiaRpc Still Image Acquisition Events
Running WinDefend Windows Defender Service
Running WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...
Running Winmgmt Windows Management Instrumentation
Running WinRM Windows Remote Management (WS-Manag...
Или если вам удобнее работать с отображаемыми именами, используйте параметр –Displayname.
PS C:\> get-service -DisplayName "windows a*"
Status Name DisplayName
------ ---- -----------
Stopped AllUserInstallA... Windows All-User Install Agent
Running AudioEndpointBu... Windows Audio Endpoint Builder
Running Audiosrv Windows Audio
Я должен использовать имя параметра, чтобы PowerShell воспринимал значения в качестве отображаемого имени, а не фактического имени службы. Команда будет выглядеть так:
PS C:\> get-service "windows a*"
Параметр –Name можно не печатать.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ НА УДАЛЕННЫХ КОМПЬЮТЕРАХ
До этого нас интересовало получение информации о статусе служб на локальном компьютере. Однако управление службами осуществляется на удаленных компьютерах. Если посмотреть справку по Get-Service, то можно увидеть наличие у этого командлета параметра –Computername. В данном случае подключение к удаленным компьютерам осуществляется без включения функции удаленного управления PowerShell. Если вы можете управлять службами, используя инструменты командной строки (sc.exe или консоль управления Service Manager), вы можете использовать PowerShell. Давайте взглянем на пример:
PS C:\> get-service spooler -ComputerName novo8
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Любая команда, которую я демонстрировал, можно использовать для передачи удаленному компьютеру. Даже нескольким компьютерам, если у вас есть соответствующие права на удаленном компьютере. Если вы используете PowerShell v3, то можно легко выбрать одну службу на множестве компьютеров.
PS C:\> get-service wuauserv -ComputerName chi-dc01,chi-dc02,chi-dc03
Status Name DisplayName
------ ---- -----------
Running wuauserv Windows Update
Stopped wuauserv Windows Update
Running wuauserv Windows Update
Для наглядности представления отформатируем вывод.
PS C:\> get-service wuauserv -ComputerName chi-dc01,chi-dc02,chi-dc03 | format-table Name,Status,Machinename -autosize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc03
wuauserv Stopped chi-dc02
wuauserv Running chi-dc01
Тот же самый результат, но в PowerShell v2.
PS C:\> 'chi-dc01','chi-dc02','chi-dc03'| foreach {get-service wuauserv -computername $_} | Format-Table Name,Status,Machinename -AutoSize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc01
wuauserv Stopped chi-dc02
wuauserv Running chi-dc03
ОСУЩЕСТВЛЯЕМ ФИЛЬТРАЦИЮ (ИСПОЛЬЗУЯ WHERE-OBJECT)
Фильтрация служб осуществляется с помощью командлета Where-Object (where – сокращение для командлета). Все, что нам нужно от PowerShell в этом случае, так это получить только те службы, у которых статус равен “stopped”.
PS C:\> get-service | where {$_.status -eq 'stopped'}
PowerShell получает информацию обо всех службах и передает их (с помощью “|”) в следующую команду, которая осуществляет просмотр каждого объекта. Если свойство статуса объекта равно “stopped”, она остается в конвейере (pipeline), в противном случае она из него исключается. В конце выражение PowerShell отображает те объекты, которые остались в конвейере.
Результаты приведены ниже.
Теперь давайте попробуем найти одну службу на нескольких машинах. Вывод отформатируем в таблицу.
PS C:\> get-service -computername @('chi-dc01','chi-dc02','chi-dc03') | where {$_.name -eq 'wuauserv'} | format-table Name,Status,Machinename -autosize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc02
wuauserv Running chi-dc01
wuauserv Running chi-dc03
Мы даже можем комбинировать запрос отдельных служб с их фильтрацией.
PS C:\> get-service "win*" -comp chi-dc03 | where {$_.status -eq 'running'}
Status Name DisplayName
------ ---- -----------
Running Winmgmt Windows Management Instrumentation
Running WinRM Windows Remote Management (WS-Manag...
Эта команда находит все службы на компьютере CHI-DC03, которые начинаются с ‘WIN’, но отображает только те, которые запущены.
Также можно сгруппировать объекты по свойству статуса (status property).
PS C:\> $dc03 = get-service -computername chi-dc03 | Group-Object -Property Status
Переменная $dc03 является объектом GroupInfo.
PS C:\> $dc03
Count Name Group
----- ---- -----
64 Running {System.ServiceProcess.ServiceController, Sy...
79 Stopped {System.ServiceProcess.ServiceController, Sy...
Свойство Group представляет собой коллекцию связанных служб.
PS C:\> $dc03.Get(0).group
Написанное выше проще понять, если взглянуть на скриншот.
Что касается меня, то я бы предпочел использовать хеш-таблицу.
PS C:\> $hash = get-service -computername chi-dc03 | Group-Object -Property Status -AsHashTable
PS C:\> $hash
Name Value
---- -----
Running {System.ServiceProcess.ServiceController, Sys...
Stopped {System.ServiceProcess.ServiceController, Sys...
Теперь каждое имя представляет собой свойство в хеш-таблице. Если у вас имеется опыт работы с PoweShell, вы, возможно, подумываете сделать сделующее:
PS C:\> $hash.running.count
Однако ничего не произойдет. Потому что свойство Status является просто перечислением (enumeration) для [System.ServiceProcess.ServiceControllerStatus] .NET клас и такие свойства, как Running и Stopped представляют собой целые числа. PowerShell осуществляет конвертацию, чтобы представить в более наглядной форме.
PS C:\> $hash = get-service -computername chi-dc03 | Group-Object -Property Status –AsHashTable –AsString
В чем суть параметра –AsString, на мой взгляд, достаточно очевидно. Теперь работать с хеш-таблицей стало проще.
PS C:\> $hash.running.count
62
PS C:\> $hash.running[0..3]
Status Name DisplayName
------ ---- -----------
Running ADWS Active Directory Web Services
Running AppHostSvc Application Host Helper Service
Running BFE Base Filtering Engine
Running BrokerInfrastru... Background Tasks Infrastructure Ser...
Следующей задачей на повестке дня является проверка зависимостей сервера (server dependencies).
Требуемые службы
PowerShell позволяет просто получить статус всех служб, которые требуется для данной службы, даже на удаленном компьютере.
PS C:\> get-service dns -ComputerName chi-dc03 –RequiredServices
Status Name DisplayName
------ ---- -----------
Running Afd Ancillary Function Driver for Winsock
Running Tcpip TCP/IP Protocol Driver
Running RpcSs Remote Procedure Call (RPC)
Running NTDS Active Directory Domain Services
Параметр –RequiredServices передаст объект в конвейер для каждой требуемой службы. Вы можете даже пойти дальше и проверить требуемые службы для работы данной службы.
PS C:\> get-service dns -ComputerName chi-dc03 -RequiredServices | select name,@{name="computername";expression={$_.machinename}} | get-service -RequiredServices
Status Name DisplayName
------ ---- -----------
Running RpcEptMapper RPC Endpoint Mapper
Running DcomLaunch DCOM Server Process Launcher
Параметр –Computername командлета Get-Service возьмет вывод, но только для тех объектов, у которых есть объект свойство Computername – именно поэтому я использую хеш-таблицу с Select-Object. Как мы видим проблем со службой DNS на компьютере CHI-DC03 нет.
ЗАВИСИМЫЕ СЛУЖБЫ
Мы можем сделать то же самое с зависимыми службами. Если таковых не имеется, в конвейер ничего передано не будет.
PS C:\> get-service dns -ComputerName chi-dc03 -DependentServices
PS C:\> get-service lanmanworkstation -ComputerName chi-dc03 -DependentServices
Status Name DisplayName
------ ---- -----------
Stopped SessionEnv Remote Desktop Configuration
Running Netlogon Netlogon
Running Dfs DFS Namespace
Running Browser Computer Browser
Требуемые и зависимые службы также являются частью каждого объекта службы.
PS C:\> get-service rpcss | Select *services
RequiredServices DependentServices
---------------- -----------------
{RpcEptMapper, DcomLaunch} {WwanSvc, wuauserv, WSearch, wscsvc...}
А пока Вы можете получить все зависимости для всех служб, следующая команда
PS C:\> get-service –DependentServices
Это не даст вам особо полезную информацию, поэтому я рекомендую осуществлять запрос по конкретным службам. Команда работает гораздо лучше PowerShell v3.
PS C:\> get-service dns -comp chi-dc01,chi-dc03 -RequiredServices | Sort Machinename,Name | Format-table -GroupBy machinename
Результаты видны на скриншоте ниже.
Чтобы получить подобные результаты в PowerShell v2, вам придется передать имена компьютеров (computernames) в Get-Service.
PS C:\> "chi-dc01","chi-dc03" | foreach { get-service dns -comp $_ -RequiredServices} | Sort Machinename,Name | format-table -GroupBy machinename
В следующей статье будет рассмотрен запуск, остановка и перезапуск служб.
Конец перевода.
Upd:
В посте приведены переводы статей с портала 4sysops.com
Managing Services the PowerShell way – Part 1
Managing Services the PowerShell way – Part 2
P.S. Хотим также поделиться нашей бесплатной программой для управления службами Windows – NetWrix Service Monitor. Программа отслеживает все автоматически запускаемые службы на группе серверов и в случае внезапного сбоя одной или нескольких из них отправляет уведомления по электронной почте. Функция перезапуска гарантирует, что все подконтрольные службы будут работать без простоев. Программа проста в настройке: устанавливаем, вводим имена компьютеров и указываем нужный адрес электронной почты.