Search code examples
powershellstring-parsing

Extract a value from log files


I am trying to parse logs in PowerShell from a logon monitoring product for our VDI environment. It writes a log file and it writes this line:

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

What I am trying to do is parse out just "4.03" from the string and store it in an array of values. I can select the entire string from the log file by doing:

$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++
}

Is there a better way I can do this?


Solution

  • Yes, you can just use a capture group in your Select-String pattern and grab the information.

    Here a one-liner example:

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

    Alternative, a more readable version:

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