从日志文件中提取值

时间:2016-12-15 21:17:10

标签: powershell string-parsing

我正在尝试从我们的VDI环境的登录监控产品中解析PowerShell中的日志。它写了一个日志文件并写下了这一行:

2016-12-15T14:15:02.863 INFO (0908-0bd8) [LogonMonitor::LogSummary] Logon Time: 4.03 seconds

我想要做的只是解析" 4.03"从字符串中将其存储在值数组中。我可以通过执行以下操作从日志文件中选择整个字符串:

$LogPath = "\\file-svr\Logs\"

$strings = Select-String -path $LogPath\*.txt -pattern "[LogonMonitor::LogSummary] Logon Time:" -AllMatches -simplematch

foreach ($string in $strings) {
$found = $string -match '\d\.'
if ($found) {
    $time = $matches[1]
    $array[$i] = $time
    }
$i++
}

我有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

是的,您可以在Select-String模式中使用捕获组并获取信息。

这里有单行示例:

$array = Select-String -path $scripts.tmp -Pattern "\[LogonMonitor::LogSummary\] Logon Time:\s*([\d|.]+)" | ForEach-Object { $_.Matches.Groups[1].Value }

替代方案,更强大的可读版本

$regex = "\[LogonMonitor::LogSummary\] Logon Time:\s*([\d|.]+)"

$array = Select-String -path $scripts.tmp -Pattern $regex | 
    ForEach-Object { 
        $_.Matches.Groups[1].Value 
    }

答案 1 :(得分:1)

您可以使用带有convertfrom-string

的正则表达式或模板
#----------- Detailled example ------------------------------------------

#define temple example for define informations to extracts
$template=@"
{[date]DEvent*:2016-12-15T14:15:02.863} {LevelEvent:INFO} {TypeEvent:(0908-0bd8)} {TypeMOnitor:[LogonMonitor::LogSummary]} Logon Time: {LogonTime:4.03 seconds}
{[date]DEvent*:2017-12-15T14:15:02.863} {LevelEvent:FATAL} {TypeEvent:(090d-x01y)} {TypeMOnitor:[LogonMonitor::Log2Summary]} Logon Time: {LogonTime:123455.156 seconds}
"@


#date example, you can replace by $date=gc "yourpathfilelog"
$datas=@"
2016-12-15T14:15:02.863 INFO (0908-0bd8) [LogonMonitor::LogSummary] Logon Time: 4.03 seconds
1987-09-02T01:00:00.00 WARNING (101-0bd8) [LogonMonitor::LogxxxSummary] Logon Time: 1.00 minutes
"@


#explode data
$dataexploded=$datas | ConvertFrom-String -TemplateContent $template

#note, you can the filter like you want
$dataexploded | where {$_.LevelEvent -eq "INFO"}



#----------- short example ------------------------------------------

$template=@"
{[date]DEvent*:2016-12-15T14:15:02.863} {LevelEvent:INFO} {TypeEvent:(0908-0bd8)} {TypeMOnitor:[LogonMonitor::LogSummary]} Logon Time: {LogonTime:4.03 seconds}
{[date]DEvent*:2017-12-15T14:15:02.863} {LevelEvent:FATAL} {TypeEvent:(090d-x01y)} {TypeMOnitor:[LogonMonitor::Log2Summary]} Logon Time: {LogonTime:123455.156 seconds}
"@

gc "c:\temp\myfile.log" | ConvertFrom-String -TemplateContent $template | where {$_.LevelEvent -eq "INFO"}