List windows services powershell

The services in Windows can be listed using the Service Manager tool.

To start the Service Manager GUI, press ⊞ Win keybutton to open the “Start” menu, type in services to search for the Service Manager and press Enter to launch it.

The services can also be listed using the command-line prompt (CMD) or the PowerShell.

In this note i am showing how to list the services and how to search for a specific service in Windows using the command-line prompt (CMD) or the PowerShell.

Cool Tip: List processes in Windows from the CMD! Read more →

List Services Using Command Line (CMD)

List all services:

C:\> sc queryex type=service state=all

List service names only:

C:\> sc queryex type=service state=all | find /i "SERVICE_NAME:"

Search for specific service:

C:\> sc queryex type=service state=all | find /i "SERVICE_NAME: myService"

Get the status of a specific service:

C:\> sc query myService

Get a list of the running services:

C:\> sc queryex type=service
- or -
C:\> sc queryex type=service state=active
-or -
C:\> net start

Get a list of the stopped services:

C:\> sc queryex type=service state=inactive

Cool Tip: Start/Stop a service in Windows from the CMD & PowerShell! Read more →

List all services:

PS C:\> Get-Service

Search for specific service:

PS C:\> Get-Service | Where-Object {$_.Name -like "*myService*"}

Get the status of a specific service:

PS C:\> Get-Service myService

Get a list of the running services:

PS C:\> Get-Service | Where-Object {$_.Status -eq "Running"}

Get a list of the stopped services:

PS C:\> Get-Service | Where-Object {$_.Status -eq "Stopped"}

Was it useful? Share this post with the world!

В 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

управление службами windows из powershell

  • 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-Help Start-Service

Get-Service: получаем список служб и их состояние

Получить список и состояние (Running/Stopped) службы на локальном или удаленном компьютере можно с помощью командлета Get-Service. Параметр -Name позволяет делать отбор по имени службы. Имя службы можно задать с использованием подстановочного символа *.

Get-Service просмотр состояния служб

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

Get-Service поиск по имени службы

.

Командлет 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 *

вывести все свойства службы windows

Командлет Select-Object позволит вывести определенные свойства службы. Например, нам нужно вывести имя, статус и доступные возможности службы Spooler:

Get-Service Spooler | Select DisplayName,Status,ServiceName,Can*

Get-Service - можно ли перезапускать, приостаналивать службу windows

Командлет Get-Service имеет два параметра, которые позволяют получить зависимости служб:

  • Параметр -DependentServices позволяет вывести службы, которые зависят от данной службы;
  • Параметр -RequiredServices позволяет вывести службы, от которых зависит данная служба.

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

Get-Service –Name Spooler -RequiredServices

Get-Service RequiredServices зависимости служб в windows

Следующая команда выводит службы, которые зависят от службы Spooler:

Get-Service –Name Spooler -DependentServices

Get-Service DependentServices

При необходимости найти службы с определенным состоянием или параметрами, используйте командлет Where-Object. Например, получим список запущенных служб со статусом Running:

Get-Service | Where-Object {$_.status -eq 'running'}

Get-Service | Where-Object status -eq 'running' - вывести запущенные службы

Для вывода служб с типом запуска Manual, выполните команду

Get-Service | Where-Object {$_.starttype -eq '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.

Командлет Stop-Service - остановит службу

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

Cannot stop service because it has dependent services. It can only be stopped if force flag set.

Stop-Service - ошибка 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

остановить несколько служб из powershell

Командлет Start-Service запускает остановленные службы:

Start-Service -Name spooler -PassThru

Start-Service -запуск службы

Служба не запустится, если есть остановленные зависимые службы. Чтобы их найти и включить:

get-service samss | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}

Start-Service запустить службу и все зависимые службы

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

Get-Service samss | Format-List name, canpauseandcontinue

Get-Service canpauseandcontinue

Чтобы отобразить список всех служб, работа которых может быть приостановлена, введите команду:

Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}

список служб, разрешающих приостановку

Приостановим службу SQLBrowser:

Suspend-Service -Name SQLBrowser

Suspend-Service

Для возобновления работы приостановленной службы служит командлет Resume-service:

Resume-Service -Name SQLBrowser

Resume-Service

Следующая команда возобновляет работу всех приостановленных служб:

get-service | where-object {$_.Status -eq "Paused"} | resume-service

Командлет Restart-Service перезапускает службу:

Restart-Service -Name spooler

Restart-Service - перезапуск службы windows

Эта команда запускает все остановленные сетевые службы компьютера:

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

Set-Service включить автозапуск для службы

Можно перевести службу на ручной (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"

New-Service создать новую службу в windows

С помощью параметра Get-WmiObject получим информацию о режиме запуска и описание службы

get-wmiobject win32_service -filter "name='testservice'"

get-wmiobject win32_service -filter "name='testservice'"

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

Set-Service -Name TestService -Description ‘My Service’ -StartupType Manual

Set-Service - изменить тип запуска службы

Чтобы удалить службу используйте команду

(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.GetMethodParameters

$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 аккаунта. Пароль при этом не указывается.

Invoke-WmiMethod - запуск службы из под другого пользователя

Как видите, PowerShell позволяет легко управлять службами Windows. Можно создавать, останавливать, запускать и возобновлять службы, менять их свойства. Большинство командлетов позволяют управлять службами на удаленных компьютерах.

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.

  1. To use the queryex command, run Command Prompt as an Administrator. You can find the app by searching cmd in the start menu.

  1. 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

  1. 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:”

  1. By default, the command lists all active processes. To look for inactive ones, modify the state parameter:

sc queryex type=service state=inactive

  1. 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.

  1. 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).

  1. 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.

  1. 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”

  1. 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

  1. 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.

  1. 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

  1. 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.

  1. 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

  1. Starting a service goes similarly:

Start-Service -Name Spooler

  1. If a service isn’t working correctly, you can also choose to restart it:

Restart-Service -Name Spooler

  1. 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

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

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

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

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

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

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

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

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,

GetService | SortObject 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.

GetService Name winmgmt,sshd,sshagent

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,

GetService 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.

GetService | WhereObject {$_.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”.

GetService | SelectObject 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:

GetService | WhereObject {$_.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.

GetService 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.

GetService Name «vmi*» | OutGridView

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.

GetService | WhereObject {$_.Status eq «Running»} | OutFile «. \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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Все версии операционной системы windows
  • Как установить windows 10 на внешний ssd диск с usb разъемом
  • Долгая загрузка windows 10 при включении amd
  • Диспетчер сервера windows server 2008 r2
  • Как сделать интерактивный рабочий стол windows 10