- 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 pull physical path of a Windows Service using Get-Service command
- 5 Answers 5
- Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
- Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
- Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
- Установка с помощью PowerShell Install using PowerShell
- Удаление с помощью PowerShell Uninstall using PowerShell
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 pull physical path of a Windows Service using Get-Service command
I need to pull Physical Execution paths of all the Windows Services on a Set of Servers, that run on Win 2k8. As, the powershell version that is shipped with this OS is 2.0, I wanted to use Get-service command instead of Get-WmiObject. I know that I can pull the physical path using the command given below
I donot want this command to pull the physical path but wanted to use Get-Service command that comes with PS Version 2.0.
Any help would be much appreciated.
5 Answers 5
Even with PowerShell 3, I don’t see a way to get it with Get-Service.
This 1-liner will get you the pathname, albeit with a little less of the preferred «filter left» behavior:
Or, if you want just the string itself:
I wanted to do something similar, but based on searching / matching the path of the process running under the service, so I used the classic WMI Query syntax, then passed the results through format-table:
You’re welcome to turn this into a one-liner by skipping defining and passing $pathWildSearch, or you could just back gwmi statement up to continue after the semi-colon.
@alroc did good, but there’s no reason to filter all services. Querying WMI is like querying a DB, and you can just ask WMI to do the filtering for you:
To explore all of the meta available for that service:
Perhaps little less verbose,
This should work on command prompt as well, not just powershell.
Or else if you have process name itself you could do:
To read process path you would need permission, so mostly I have better luck with service name.
I was never able to do this through the Get-Service command but if your service runs as it’s own process then you can use the Get-Process command for this via the following code:
Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
Если вы разрабатываете службу Windows с помощью .NET Framework, вы можете быстро установить приложение службы с помощью служебной программы командной строки InstallUtil.exe или PowerShell. If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Если вы являетесь разработчиком и хотите создать службу Windows, которую пользователи могут устанавливать и удалять, можно использовать набор инструментов WiX или коммерческие средства, такие как Advanced Installer, InstallShield или другие. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. См. сведения о создании пакета установщика (классическое приложение Windows). For more information, see Create an installer package (Windows desktop).
Если вы хотите удалить службу на своем компьютере, не выполняйте процедуру, описанную в этой статье. If you want to uninstall a service from your computer, don’t follow the steps in this article. Вместо этого определите, какая программа (или программный пакет) установила эту службу, а затем выберите Приложения в параметрах, чтобы удалить эту программу. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Следует отметить, что многие службы являются составной частью ОС Windows. Если их удалить, это может привести к нестабильной работе системы. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
Чтобы использовать процедуру, описанную в этой статье, сначала необходимо добавить установщик службы в свою службу Windows. To use the steps in this article, you first need to add a service installer to your Windows service. Дополнительные сведения см. в разделе Пошаговое руководство: создание диспетчера служб Windows. For more information, see Walkthrough: Creating a Windows service app.
Проекты служб Windows нельзя запускать непосредственно из среды разработки Visual Studio путем нажатия клавиши F5. You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Перед запуском проекта необходимо установить службу в проекте. Before you can run the project, you must install the service in the project.
Запустите обозреватель сервера и убедитесь, что служба установлена или удалена. You can use Server Explorer to verify that you’ve installed or uninstalled your service.
Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Запустите InstallUtil.exe из командной строки, указав исполняемый файл проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
Если вы используете командную строку разработчика для Visual Studio, системный путь должен указывать на файл InstallUtil.exe. If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Если это не так, можно добавить его в путь или использовать полный путь для его вызова. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. Этот инструмент устанавливается вместе с платформой .NET Framework в папку %WINDIR%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
Пример: For example:
- Для 32-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: если каталог установки Windows — C:\Windows, по умолчанию используется путь C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe. For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
- Для 64-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: по умолчанию используется путь C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe. For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Запустите InstallUtil.exe из командной строки, указав выходные данные проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s output as a parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Установка с помощью PowerShell Install using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Выполните командлет New-Service, указав в качестве параметров выходные данные проекта и имя службы. Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Удаление с помощью PowerShell Uninstall using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Выполните командлет Remove-Service, указав в качестве параметра имя службы. Run the Remove-Service cmdlet with the name of your service as parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.