PowerShell 替换正则表达式

Bra*_*rad 5 regex powershell replace

我有一个select-string正在 IIS 日志中搜索特定字符串并返回上面 2 行和下面一行的程序。

结果如下:

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 - - - - 
Run Code Online (Sandbox Code Playgroud)

请注意,第三行开头表示这是匹配的>行。select-string

-replace我正在尝试替换>它,< font color="red">$1< /font>但我的替换似乎不起作用。

这是我的代码:

$results = $results -replace "(^> )(.*)$", "< font color='red'>$1< font>" 
Run Code Online (Sandbox Code Playgroud)

任何 PowerShell 正则表达式专家都可以告诉我为什么我的正则表达式不匹配吗?

Bar*_*ekB 2

你应该开始思考对象而不是文本,因为你看到的只是格式化的对象,而不是 select-string 的实际输出。不要解析此输出 - 使用您获得的对象(Get-Member 会让您发现它们)。

我想这应该可以满足您的需要:

# 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>"
Run Code Online (Sandbox Code Playgroud)

HTH巴泰克