Monthly Archive

Categories

Its all in context

I spent part of this afternoon using select-string to track down where particular settings occur in GPOs.  Use the SDM GPMC cmdlets to dump the settings to xml and then use select-string on the xml.  So much easier than wading through the GUI.

In PowerShell v1 select-string returned the line containing the text we are searching for

PS> Select-String *.txt -Pattern "target text"

file1.txt:9:some text with what we want - - - target text
file2.txt:15:some text with what we want - - - target text

In v2 we can get the context of the target ie lines before and after

PS> Select-String *.txt -Pattern "target text"   -Context 0,1

> file1.txt:9:some text with what we want - - - target text
  file1.txt:10:and lest we forget -- we want the context as well
> file2.txt:15:some text with what we want - - - target text
  file2.txt:16:and lest we forget -- we want the context as well

Note the > to show the line with the actual text.  Context is specified as number of lines before, lines after the target.

This is fine but what if you want to actually separate out the results.  At the moment we get file name, line number and the line.  what would be good would be data separated out.  First go is

Select-String *.txt -Pattern "target text"   -Context 0,1 | Select FileName, Line, Context

This doesn’t work as the object type is returned for the context.  We can use get-member to dig into the context and then do something like this

001
002
003
Select-String *.txt -Pattern "target text"   -Context 0,1 | foreach {
"{0} {1} {2} {3} " -f $_.FileName, $_.LineNumber, $_.Line, $($_.Context.PostContext)
}

 

The context collection has both a Post context and a Precontext member.   Once we have the data we can format it at leisure.

The context could be used in a number of places eg picking DNS servers out of ipconfig files.

Select-string is a very useful cmdlet and one that it pays to get to know.  BTW the pattern is actually converted to a regular expression!

Technorati Tags: ,

Leave a Reply