Saturday, 25 April 2015

Returning Only Matching Text With Select-String

Let’s face it - Select-String can be a maddeningly frustrating cmdlet.  I think a lot of people with a DOS or VbScript background expect it to work like findstr which just returns the matching text you were looking for.  Select-String, on the other hand, is ever so helpful and returns the file name, the line number of the match and THEN the matching text all in one line.  I remember banging my head against the wall when I first tried to figure it out so here it is, recorded for posterity.

You’re Giving Me Too Much Information

Let’s take a look at the overly helpful information returned by default.  We’re looking for the string “PickMe” in a file called testfile.txt which has the following lines in it:

PickMeImTheStringYouWant
IgnoreMe
IgnoreMeToo
PickMeImTheStringYouWantAsWell

This is what we get returned when we run Select-String looking for the pattern “PickMe”:

image

Goodness, that’s a lot of info.  Problem is, I already know the file name since I used it in the command and I don’t really care about what line my matches are on – I just want to know if there were any matches and what they were!

This is how we get only the information we’re after:

image

That’s all there is to it - the Line property is the key!  There are other properties you can use as well although I find Line is the one I use almost all the time.  To see the other methods and properties, run the command shown below:

image

No comments:

Post a Comment