1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

<Windows: Event log> PowerShell から PC の【電源 ON/OFF】の履歴を取得する

Last updated at Posted at 2025-10-28

※このスクリプトは「高速スタートアップ」を考慮していません。

 高速スタートアップを有効にしている場合は PCを起動した日時とシャットダウンした日時を確認する方法 が参考になると思います。

PowerShell
# 現在時刻から遡る日数
$Days  = 4
# 取得するログの数
$Count = 200
# 対象とするイベントID
$IDs   = @(7002, 7001, 6008, 6006, 6005, 1074, 13, 12)

$EventLog = Get-WinEvent -Oldest -MaxEvents $Count -FilterHashtable @{
    LogName   = "System"
    ID        = $IDs
    StartTime = (Get-Date).AddDays(-$Days)
} | Sort-Object TimeCreated

$BlankBox = [PSCustomObject][ordered]@{
    発生日時  = $null
    イベント  = $null
    提供元   = $null
    メッセージ = $null
}
$BeginBox = [PSCustomObject][ordered]@{
    発生日時  = "Windows is starting"
    イベント  = "up" + "   #- - - - - - - - -"
    提供元   = "- - - - - - -#"
    メッセージ = $null
}
$CeaseBox = [PSCustomObject][ordered]@{
    発生日時  = "Windows is shutting"
    イベント  = "down" + " #- - - - - - - - -"
    提供元   = "- - - - - - -#"
    メッセージ = $null
}

$OutputList = [Collections.Generic.List[PSObject]]::new()
:HEAD foreach ($Event in $EventLog) {
    switch ($Event.Id) {
        7002 { $Description = "[$_] userサインアウト"; break }
        7001 { $Description = "[$_] userサインイン "; break }
        6008 { $Description = "[$_] 前回:不正な終了"; break }
        6006 { $Description = "[$_] イベントログ停止"; break }
        6005 { $Description = "[$_] イベントログ開始"; break }
        1074 { $Description = "[$_] 電源遮断/再起動"; break }
          13 { 
            if ($Event.ProviderName.Contains("Wininit")) {
                $Description = ""; continue HEAD
            } else {
                $Description = "  [$_] OSシャットダウン"
            }
            break 
        }
          12 { $Description = "  [$_] OSスタートアップ"; break }
        default { $Description = "[$_] Other references" }
    }
    $Provider   = $Event.ProviderName -replace "^$([regex]::Escape("Microsoft-Windows-"))"
    $Formatting = ($Event.Message -replace "\r?\n").Trim()

    if ($Description -match "OSスタートアップ") { 
        $OutputList.Add($BeginBox) 
    }
    $OutputList.Add([PSCustomObject][ordered]@{
        発生日時  = $Event.TimeCreated
        イベント  = $Description
        提供元   = $Provider
        メッセージ = $Formatting
    })
    if ($Description -match "OSシャットダウン") { 
        $OutputList.AddRange([PSObject[]]($CeaseBox, $BlankBox, $BlankBox)) 
    }
}
# $OutputList | Format-Table -AutoSize -Wrap
$OutputList | Format-Table 発生日時,イベント,提供元
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?