Friday, January 7, 2011

Keeping track of system freezes with PowerShell

A colleague has been having some problems with her Windows 7 x64 machines freezing and requiring a forced shut-down. Unfortunately, these are not logged in the reliability monitor, but they are logged in the event log. I used PowerShell to process the event log to find start-up and shut-down events:

#Based on information from http://support.microsoft.com/kb/196452

$results = @()

function GetResult($time, $message)
{
    return New-Object psobject -Property @{ Time = $time; Message = $message };
}

Get-EventLog System | ? { $_.Source -eq "EventLog" -and 6006,6008,6009 -contains $_.EventId } | % {
    $item = $_
    switch($_.EventID)
    {
        6006 { $results += (GetResult $item.TimeGenerated "Clean shutdown") }
        6008 
        { 
            if(-not ($item.Message -match "^The previous system shutdown at (.*) on (.*) was unexpected.$"))
            {
                throw "Invalid format."
            }
            $c = ($matches[2] -replace '\u200E','') + " " + ($matches[1] -replace '\u200E','');  #not sure why, but it includes the unicode character 'LEFT-TO-RIGHT MARK'
            $dt = [datetime]::parse($c)
            $results += (GetResult $dt "Dirty shutdown")
        }
        6009 { $results += (GetResult $item.TimeGenerated "Start-up") }
    }
}

$results | sort Time -Descending

Running the script will create output similar to this:
.\ShutdownEvent.ps1

Message        Time
-------        ----
Start-up       7/01/2011 13:34:38
Dirty shutdown 7/01/2011 13:18:22
Start-up       7/01/2011 08:18:25
Clean shutdown 6/01/2011 16:44:41
Start-up       6/01/2011 08:19:52
Clean shutdown 5/01/2011 16:42:38
Start-up       5/01/2011 08:18:23
Clean shutdown 31/12/2010 16:21:51
Start-up       31/12/2010 08:50:07
Clean shutdown 30/12/2010 16:36:55
Start-up       30/12/2010 08:49:39
Clean shutdown 29/12/2010 16:37:34
Start-up       29/12/2010 08:50:48
Clean shutdown 24/12/2010 09:52:04
Start-up       24/12/2010 08:46:15
Clean shutdown 23/12/2010 13:25:19
Start-up       23/12/2010 08:02:46
Clean shutdown 22/12/2010 16:37:40
Start-up       22/12/2010 08:02:18
Clean shutdown 21/12/2010 16:35:55
Start-up       21/12/2010 08:02:13
Clean shutdown 20/12/2010 16:32:50
Start-up       20/12/2010 08:01:52


You can also filter the output, for example to only show dirty shut-down events:

.\ShutdownEvent.ps1 | ? { $_.Message -match 'Dirty.*' }

Message        Time
-------        ----
Dirty shutdown 7/01/2011 13:18:22
Dirty shutdown 16/09/2010 08:23:41
Dirty shutdown 9/09/2010 11:04:31
Dirty shutdown 19/07/2010 11:35:27
Dirty shutdown 14/07/2010 13:52:24
Dirty shutdown 8/07/2010 13:40:26
Dirty shutdown 7/05/2010 08:22:57

0 comments:

Post a Comment