Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Parse LogFile Using PowerShell

$
0
0

Hello,

I am new to PowerShell, and trying to parse Log file for the most recent [ERROR] keyword . 

Content of my log file is as follows

[ERROR] 2013-12-23 19:46:32
[ERROR] 2013-12-24 19:46:35
[ERROR] 2013-12-24 19:48:56
[ERROR] 2013-12-24 20:13:07

Function CheckLogs()

{
    param ([string] $logfile)
    if(!$logfile) {write-host "Usage: ""<Log file path>"""; exit}
    cat $logfile | Select-String "ERROR" -SimpleMatch | select -expand line |
         foreach {
                    $_ -match '(.+)\s\[(ERROR)\]\s(.+)'| Out-Null 
                    new-object psobject -Property @{Timestamp = [datetime]$matches[1];Error = $matches[2]} |
                    where {$_.timestamp -gt (get-date).AddDays(-1)}
                    $error_time = [datetime]($matches[1])
                    if ($error_time -gt (Get-Date).AddDays(-1) )
                    {
                        write-output "CRITICAL: There is an error in the log file $logfile around 
                                     $($error_time.ToShortTimeString())"; exit(2)
                    } 
                 }
  write-output "OK: There was no errors in the past 24 hours." 
}
CheckLogs "C:\Log.txt" #Function Call

After executing above script, I am getting the below error, please advise.

 $error_time = [datetime]($matches[1])
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
 
Cannot index into a null array.
At C:\PS\LogTest.ps1:10 char:21
+                     new-object psobject -Property @{Timestamp = 
[datetime]$match ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
 
Cannot index into a null array.
At C:\Test\LogTest.ps1:12 char:21
+                     $error_time = [datetime]($matches[1])
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray


Viewing all articles
Browse latest Browse all 15028

Trending Articles