gather last reboot events

 function Write-Log {

    param (

        [string]$Message,

        [string]$LogFilePath = "C:\Windows\Logs\Software\LastRebootEvent.log"

    )

    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

    $LogMessage = "$Timestamp : $Message"

    

    $LogDir = [System.IO.Path]::GetDirectoryName($LogFilePath)

    if (!(Test-Path -Path $LogDir)) {

        New-Item -ItemType Directory -Path $LogDir -Force

    }


    

    $LogMessage | Out-File -FilePath $LogFilePath -Append -Encoding UTF8

}



Write-Log "Starting to gather last reboot events..."


# Event IDs to filter: 1074 (user/system initiated restart/shutdown), 6005 (system startup), 6006 (clean shutdown), 6008 (unexpected shutdown)

$EventIDs = @(1074, 6005, 6006, 6008)


# Get events from the System log within the last 90 days

$Events = Get-WinEvent -FilterHashtable @{

    LogName   = 'System'

    StartTime = (Get-Date).AddDays(-90)

    ID        = $EventIDs

} | Select-Object TimeCreated, ID, ProviderName, Message


Write-Log "Retrieved $($Events.Count) events from the System log."


foreach ($Event in $Events) {

    $LogEntry = "Event Time: $($Event.TimeCreated), Event ID: $($Event.ID), Provider: $($Event.ProviderName), Message: $($Event.Message)"

    Write-Log $LogEntry

}


Write-Log "Reboot events logging completed."


Comments

Popular posts from this blog

powershell script to export applications and its requirement in weird way

get-allrecent udpated logs

TASK sequence duration report