PowerShell Replace Regex

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:

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:

$results = $results -replace "(^> )(.*)$", "< font color='red'>$1< font>" 

Can any PowerShell regex gurus out there tell me why my regular expression isn't matching?


Solution 1:

If $a contains the value of your third line try :

$a -replace '(^>)(.*)','font color="red">$2<font/>'

Two things :

  1. Use single qutes for your RegEx
  2. The index of groups begin at 1

Solution 2:

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:

# Prepare test data...
$tring = @'
alfa
beta
gamma
delta
alfa
beta
alfa
beta
'@.Split("`n")

# Display results with actually matching line highlighted in red...
"<body>"
$tring | select-string 'delta' -Context 2,2 | foreach {
    $_.Context.PreContext
    "<font color='red'>$($_.Line)<font>"
    $_.Context.PostContext
}
"</body>"

HTH Bartek