Powershell, help read log file to get specific keywords

时间:2016-04-04 18:04:13

标签: regex powershell

How to read a log file to get keyword fail and timestamp from date then print it to csv?

example: I have a file test.txt which contains

20160201-00:00:00 Success ..
20160201-11:11:11 Fail..

I want a report showing for all fails

Date          Time       Result
----------
20160201      11:11:11   Fail

Appreciate your help!

2 个答案:

答案 0 :(得分:0)

Something like:

(gc log.txt) -match 'fail' | % { 
    $_ -match '^([^ ]+ )(.+)'
    $matches[1] + ',' $matches[2] | out-file -Append out.csv
}

This is very close to what you want, you just need to polish it a bit.

答案 1 :(得分:0)

You first have to read the text file using the Get-Content cmdlet. To parse the Logs, you could use the following Regex (Demo):

(\d{8})-(\d{2}:\d{2}:\d{2})\s+(\w+)

In the following example, I iterate over the matches using the Foreach-Object cmdlet (alias %) and create a new Object with the desired properties. To filter only the Fail Reports, you can use the Where-Object cmdlet (alias Where). To convert the Object to a CSV, you can use the Export-CSV cmdlet:

$content = Get-Content 'C:\Yourpathto\test.txt'
$regex = '(\d{8})-(\d{2}:\d{2}:\d{2})\s+(\w+)'
[regex]::Matches($content, $regex) | % {  
    [PSCustomObject]@{
            Date = $_.Groups.Value[1]
            Time = $_.Groups.Value[2]
            Result = $_.Groups.Value[3]
            }
 } | Where Result -eq 'Fail' | Export-Csv -Path c:\test.csv