Simple Text-Based Filtering a la grep (Part 1)

by Jun 3, 2022

PowerShell is object-oriented so there’s not much text filtering and regex magic required compared to Linux and grep. Yet occasionally, it would be efficient and comfortable to filter command object by simple text patterns.

And it works -kinda. PowerShell does come with a grep-like command, the cmdlet Select-String. While it excels at filtering file content, it isn’t useful at first when trying to filter command output.

Let’s assume you’re interested in running services only. Filtering for “running” yields nothing:

 
PS> Get-Service | Select-String Running 
 

That’s not the fault of Select-String, though. Select-String needs text input, and cmdlets typically return rich objects, not text. By converting command output to string, all works fine:

 
PS> Get-Service | Out-String -Stream | Select-String Running

Running  AdobeARMservice    Adobe Acrobat Update Service          
Running  AgentShellService  Spiceworks Agent Shell Service        
Running  Appinfo            Application Information               
Running  AppMgmt            Application Management                
Running  AppXSvc            AppX Deployment Service (AppXSVC)  
...   
 

That’s awesome if you don’t mind that the end result is now plain text. That seems to be the price for simple text filtering.

No, it isn’t. You can create your own filter command that *temporarily* converts incoming objects to text, does the text pattern match, and then returns the unchanged rich objects. Sounds simple, and it really is. Here is PowerShell’s grep:

filter grep ([string]$Pattern)
{
    if ((Out-String -InputObject $_) -match $Pattern) { $_ }
}

Run the code, then try it:

 
PS> Get-Service | grep running

Status   Name               DisplayName                           
------   ----               -----------                           
Running  AdobeARMservice    Adobe Acrobat Update Service          
Running  AgentShellService  Spiceworks Agent Shell Service        
Running  Appinfo            Application Information               
Running  AppMgmt            Application Management 
...   
 

It’s beautifully simple to use and, best of all, outputs rich objects so you can still access its properties

 
PS> Get-Service | grep running | Select-Object Name, StartType, Status

Name                                        StartType  Status
----                                        ---------  ------
AdobeARMservice                             Automatic Running
AgentShellService                           Automatic Running
Appinfo                                        Manual Running
AppMgmt                                        Manual Running
AppXSvc                                        Manual Running
AudioEndpointBuilder                        Automatic Running   
 

Twitter This Tip! ReTweet this Tip!