2016-12-15 117 views
1

我想從我們的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

是的,您可以在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

太棒了!我正在想辦法解決這個問題。非常感謝。這工作完美 – Koecerion

+0

你有足夠接近。不用謝。 –

0

你可以使用正則表達式或模板convertfrom串

#----------- Detailled example ------------------------------------------ 

#define temple example for define informations to extracts 
[email protected]" 
{[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" 
[email protected]" 
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 ------------------------------------------ 

[email protected]" 
{[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"}