Microsoft partner of the year icon


If you aren’t familiar with sed and grep you may want to stop reading here. If you are and this is bringing Unix flashbacks, you should read on. I started my career on Unix systems and quickly found that grep and sed were just part of getting the job done and I ended up using them for pretty much everything. When I started working with PowerShell and I was piping output around I found myself quickly missing good old sed and grep. As a quick summary, grep just matched something in the text. As an example, directory a file pipe it to grep for part of the name of the file that you were looking for. Sed provided a way to quickly replace a value within a file with something else (such as replace all instances of XYZCO with ABCCO).

From this blog post I found that you can define a filter which you can then use to perform something like grep. His filter is as follows:

filter grep($keyword) { if ( ($_ | Out-String) -like “*$keyword*”) { $_ } }

Using the blog post concept, I was able to build a similar filter for sed. The following is my filter:

filter sed($before,$after) { %{$_ -replace $before,$after} }

For examples of this let’s start with grep – the PowerShell below lists all services which include the word “Background”

Get-Service | grep Background



Or another example of this, listing all SCOM classes which include the word database as shown below (get-scomclass | grep database).

Or a search for all SCOM classes which include “SQL Database” (get-scomclass | grep “SQL database”).

For examples of this let’s go next to sed – the PowerShell below lists all processes and changes the reference to w32time to Timer.

Get-Service | sed w32time Timer

Summary: By putting these filters into the top of my scripts (or using them when I launch PowerShell) I’ve been able to take most of the times where I would need a grep or a sed and utilize this approach to accomplish the same type of functionality.

Additional reference: