Question:
I have a select-string
which is searching an IIS log for a particular string and returning the 2 lines above and one line below.
Results look like this:
1 2 3 4 5 |
2012-06-15 18:26:09 98.138.206.39 OutboundConnectionResponse SMTPSVC1 WEB10 - 25 - - 220+mta1083.sbc.mail.ne1.yahoo.com+ESMTP+YSmtp+service+ready 0 0 60 0 218 SMTP - - - - 2012-06-15 18:26:09 98.138.206.39 OutboundConnectionCommand SMTPSVC1 WEB10 - 25 EHLO - WEB10.DOMAIN>COM 0 0 4 0 218 SMTP - - - - > 2012-06-15 18:26:09 74.125.244.10 OutboundConnectionResponse SMTPSVC1 WEB10 - 25 - - 550+IP+Authorization+check+failed+-+psmtp 0 0 41 0 218 SMTP - - - - 2012-06-15 18:26:09 74.125.244.10 OutboundConnectionCommand SMTPSVC1 WEB10 - 25 RSET - - 0 0 4 0 218 SMTP - - - - |
Note the third line begins with >
denoting that’s the line that select-string
matched upon.
I am trying to do a -replace
on the >
to replace it with < font color="red">$1< /font>
but my replace doesn’t seem to work.
Here’s my code:
1 2 |
$results = $results -replace "(^> )(.*)$", "< font color='red'>$1< font>" |
Can any PowerShell regex gurus out there tell me why my regular expression isn’t matching?
Answer:
You should start thinking-object rather than text, because what you see is only formated object, not actual output of select-string.
Instead of parsing this output – use objects that you get (Get-Member will let you discover them).
I guess this should do what you need:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Prepare test data... $tring = @' alfa beta gamma delta alfa beta alfa beta '@.Split("`n") # Display results with actually matching line highlighted in red... "" $tring | select-string 'delta' -Context 2,2 | foreach { $_.Context.PreContext "$($_.Line)" $_.Context.PostContext } "" |
HTH
Bartek