Posted On July 5, 2022

PowerShell: Gather Information About Windows Shutdown Reasons

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Gather Information About Windows Shutdown Reasons

Copy and Paste this to See Result(s):

$computername=$env:computername
$limitEventsCount=40000
$daysSearchLimit=30

function getWindowsShutdownReason{
    param(
        $computername=$env:computername,
        $limitEventsCount=10000,
        $daysSearchLimit=7
    )
    try{
        $events = Get-WinEvent -ComputerName $computername -FilterHashtable @{
            Logname = 'system'
            Id = '1074', '6008'
            StartTime = (Get-Date).AddDays(-$daysSearchLimit)
        } -MaxEvents $limitEventsCount -ErrorAction Stop
        # There are 2 types of shutdown codes (1074 = user initiated; 6008 = abrupt shutdowns)
        foreach ($event in $events) {
            if ($event.Id -eq 1074) {
                [PSCustomObject]@{
                    TimeStamp    = $event.TimeCreated
                    ComputerName = $computername
                    UserName     = $event.Properties.value[6]
                    ShutdownType = $event.Properties.value[4]
                }
            }
            if ($event.Id -eq 6008) {
                [PSCustomObject]@{
                    TimeStamp    = $event.TimeCreated
                    ComputerName = $computername
                    UserName     = $null
                    ShutdownType = 'unexpected shutdown'
                }
            }
        }
    }catch{
        write-warning $_
    }    
}

getWindowsShutdownReason $computername $limitEventsCount $daysSearchLimit

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Update Windows Computers

There's a more updated version available. <# Update-Windows-Computers-v0.11.ps1 # # Purpose: trigger Microsoft Updates on…

Using Python to Automate Video Playing on Ubuntu

This little snippet was generated using ChatGPT with more than a little bit of prompting…

PowerShell: Disable Windows Defender

Simultaneous Uninstalls: # removeWindowsDefender.ps1 # Version 0.02 $computerNames=@( 'server1', 'server2' ) function removeWindowsDefender($computerNames){ function uninstallWindefend($computername){…