尝试使用PowerShell解析IIS日志时进行模式匹配

时间:2014-07-12 17:37:51

标签: regex powershell

我尝试使用PowerShell解析包含大约6000行的IIS日志文件。样品行如下,

2014-07-11 10:12:18 172.20.154.136 POST /STAD/Listener/DocFWBOLListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 3790
2014-07-11 10:12:25 172.20.154.136 POST /STAD/Listener/DocFWBOLListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 2730
2014-07-11 10:12:31 172.20.154.136 POST /STAD/Listener/DocBOLAdviceConfirmListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 2386
2014-07-11 10:12:34 172.20.154.136 POST /STAD/Listener/DocBOLAdviceConfirmListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 3244
2014-07-11 10:12:34 172.20.154.136 POST /STAD/Listener/DocFWBOLListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 3900
2014-07-11 10:12:41 172.20.154.136 POST /STAD/Listener/DocFWBOLListener.asp - 80 - 172.20.44.112 Java/1.6.0_20 200 0 0 2870

我需要匹配POST /STAD/Listener/DocBOLAdviceConfirmListener.asp并获取时间字段,这是每行中的最后一个条目。我编写了以下脚本来解析文件,但模式匹配失败并返回cannot index into null array错误。有人可以帮助我使用正则表达式部分。感谢。

$Filepath = "C:\inetpub\logs\logfiles\W3SVC1"
$Filen = Get-ChildItem -Path $Filepath | Select-Object -Last 1
$Filename = ($Filen).FullName
$Pat1 = "^.*(DocBOLAdviceConfirmListener).* (\d{1,})$" 
#$Pat2 = "^.* (\d{1,})$"
#$data = ''
$Count1 = 0
    $stream = New-Object System.IO.FileStream -ArgumentList $Filename, 'Open', 'Read', 'ReadWrite'
    $reader = New-Object System.IO.StreamReader -ArgumentList $stream, $true
    $reader.BaseStream.Seek(0, 'Begin')
    while (-not $reader.EndOfStream) {
        $line = $reader.ReadLine()

        #$line
        if ([regex]::Matches($line,$Pat1,"IgnoreCase")) { 
            $DocBolACLValue = $matches[2]
            if ($DocBolACLValue -gt 3000) {
                $Count1 += 1
            }
        }
    }

    $reader.Close()
    $stream.Close()
    $Count1

1 个答案:

答案 0 :(得分:0)

$Filepath = "C:\inetpub\logs\logfiles\W3SVC1"
$Filen = Get-ChildItem -Path $Filepath | Select-Object -Last 1
$Filename = ($Filen).FullName
$contents = get-content $Filename

foreach($item in $contents)
{
    $regex1 = [regex]::Match($item,"\d+:\d+:\d+","ignorecase")
    $regex2 = [regex]::Match($item,"/STAD/Listener/DocBOLAdviceConfirmListener.asp","ignorecase")
    if($regex2.Success -eq $true)
    {
        $combined = $regex1.value + " " + $regex2.value
        $combined #displays matching lines
    }   
}

我希望这适合你。

T.CK