kamokoba
kamokoba

Reputation: 597

Powershell: how to "grep" the output of a command by using "select-string"?

When I issue get-service command, I get the entire list of services.

I want to list only a specific service.

The service in question is being listed in the output of get-service:

Running  nginx              nginx

But if I try to use any of the following:

PS C:\Users\x> get-service | Select-String "nginx"
PS C:\Users\x> get-service | Select-String -Pattern "nginx"
PS C:\Users\x> get-service | Select-String -Pattern 'nginx'

I get no output.

So how do I "grep" in Powershell?

Upvotes: 1

Views: 1434

Answers (2)

boxdog
boxdog

Reputation: 8442

An essential thing to note is that PowerShell cmdlets always output objects, not simple strings - even when the output seems to be a string, it is really a System.String object. You can check the type of the output of a command (and the associated properties and methods) using Get-Member:

Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
...

As mentioned by others, Get-Service (and other cmdlets) has built-in filtering for what you're trying to do, but a more general alternative, which is more flexible (though often slower) is Where-Object:

Get-Service | Where-Object {$_.Name -like 's*' -and $_.Status -eq 'Running'}

Status   Name               DisplayName
------   ----               -----------
Running  SamSs              Security Accounts Manager
Running  SCardSvr           Smart Card
Running  Schedule           Task Scheduler
Running  SecurityHealthS... Windows Security Service
Running  SENS               System Event Notification Service
...

Upvotes: 4

Civette
Civette

Reputation: 538

This should do it

Get-Service -Name "nginx"

Upvotes: 2

Related Questions