Tuesday, January 27, 2009

This is my third update to this script.  I think this script will finally push me into "programming like a real man" (e.g. with functions, params, hash arrays, throws, traps other optimizations) e.g. http://rmfdevelopment.com/PowerShell_Scripts/QueryEventFunction.ps1
Interestingly, I found System Event ID 36 breaks my script. It is a failure of the Windows Time Service and I think I have found a defect in Time/Date formatting:

## Takes Event Log queries...and finds elapsed time from event
# Default queries localhost system shutdown (EventID 6009)
# E.G. .\EventLogQueries.ps1 System 4072
# E.G .  6005..6009 | %{.\EventLogQueries.ps1 System $_ }    

if ($args[0] -eq $Null) {$Log_Type = "System"} else {$Log_Type = $args[0]}
if ($args[1] -eq $Null) {$Event_ID = 6009} else {$Event_ID = $args[1]}
write $args[1]
## TODO for remote and other properties:
## if ($args[3] = $Null) {$Computer = localhost} else {$args[3] = $Computer}

# query Event Log

$EventLog = get-eventlog -log $Log_Type | Select Message,EventID,TimeGenerated
$Event = $EventLog | ?{$_.eventID -eq $Event_ID}
$EventID = $Event | %{$_.eventID}
$Message = $Event | %{$_.Message}
$TimeGenerated = $Event | %{$_.TimeGenerated}
 
## TODO: Needs Trap or Throw for bad date or time format from Microsoft like for Event ID 36
## EventID 36 will break this script because....(??) 
## if EventID is null, discard query

if  ($LogType = "System" -and $EventID -eq 36) {$EventID = $NULL;write "Skip System EventID 36 because it breaks this script"}
if  ($EventID -ne $NULL)
{
    # Find elapsed time, total restarts, restarts/days and generate some arrays
    ## DBG::$test_EventID = $EventID[0]
    ## DBG::$test_Args_1  = $Args[1]
    ## DBG::write "Args[1]:$test_Args_1 -- Date/Time -- Elapsed Time (D.H.M.S)"
    
    write  "EventID -- Message -- Date/Time -- Elapsed Time (D.H.M.S)"
    $array_count = ($Event).count - 1
    $total_events = ($Event).count
    $curr_date = get-date
    $first_event_date = $TimeGenerated[$array_count]
    $last_event_date = $TimeGenerated[0]
    $event_time_span =($curr_date - $first_event_date)  
    $elapsed = $TimeGenerated[0..$array_count] | %{($curr_date - $_)}
    $AverageDaysBetweenEvents = $event_time_span.Days%$total_events
    
    
    ## Report Data
    ## What happens if data field is null?
    0..$array_count | %{
    $days = $elapsed[$_].days;
    $hours = $elapsed[$_].hours;
    $minutes = $elapsed[$_].minutes;
    $seconds = $elapsed[$_].seconds;
    $EventIDPrint = $EventID[$_];
    $MessagePrint = $Message[$_];
    $TimeGeneratedPrint = $TimeGenerated[$_];

    write "$EventIDPrint,$MessagePrint,$TimeGeneratedPrint,$days.$hours.$minutes.$seconds" }
    }
    
if  ($EventID -ne $NULL)
write "Number of Events:$total_events First Occurrence:$first_event_date Last Occurrence:$last_event_date Average Days Between Events:$AverageDaysBetweenEvents"
}


No comments: