Skip to content

Instantly share code, notes, and snippets.

@fheck
Last active May 5, 2019 22:56
Show Gist options
  • Save fheck/5ab39c7757a19fcecec9fc49e0dabf57 to your computer and use it in GitHub Desktop.
Save fheck/5ab39c7757a19fcecec9fc49e0dabf57 to your computer and use it in GitHub Desktop.
Informative "uptime" function for powershell on Windows
function runtime {
function extractDate($text, $type) {
$regex = '.*?' + $type + ' Time: (?:.?(\d{4}).?-.?([01]\d).?-.?([0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z))).*?'
$date = ( % {[regex]::Match($text, $regex)}).Groups
return Get-Date($date[1].Value + "-" + $date[2].Value + "-" + $date[3].Value)
}
$now = Get-Date
$bootevents = Get-WinEvent -FilterHashtable @{logname="system";providername="Microsoft-Windows-Kernel-Boot";ID=27} -ErrorAction SilentlyContinue | Sort-Object -Property "Timecreated" -Descending
$boottime = ($bootevents | Where-Object {$_.message -notlike "*0x2."} | Select -first 1).Timecreated
$wakeevents = Get-WinEvent -FilterHashtable @{logname="system";providername="Microsoft-Windows-Power-Troubleshooter";StartTime=$boottime} -ErrorAction SilentlyContinue | Sort-Object -Property "Timecreated" -Descending
Write-Host $('Runtime since last boot ({0,2:%d} days {0,2:%h} hours {0,2:%m} minutes and {0,2:%s} seconds ago):' -f ($now - $boottime));
Write-Host $(' {0,2:%d} days {0,2:%h} hours {0,2:%m} minutes and {0,2:%s} seconds.' -f (
($now - $boottime) - (New-TimeSpan -start 0 -end (Get-Date(
[long]((
$wakeevents |
ForEach { New-TimeSpan -end (extractDate $_.message "Wake") -start (extractDate $_.message "Sleep")} |
ForEach {$_.Ticks}
) | Measure-Object -Sum).sum
)))
))
$wake = ($wakeevents | Select -first 1)
if ([string]::IsNullOrEmpty($wake.message)) {
Write-Host $('No sleep since last boot')
} else {
$waketime = (extractDate $wake.message "Wake")
Write-Host $('Runtime since last wake: {0,2:%d} days {0,2:%h} hours {0,2:%m} minutes and {0,2:%s} seconds.' -f (
New-TimeSpan -end $now -start $waketime
))
$sleepmessage = (Get-WinEvent -FilterHashtable @{logname="system";providername="Microsoft-Windows-Kernel-Power";ID=42} | Sort-Object -Property "Timecreated" -Descending | Select -first 1).message
$sleepreason = (( % {[regex]::Match($sleepmessage, 'Sleep Reason: (.*)$')}).Groups)[1]
$hibernationevents = $bootevents | Where-Object {$_.message -like "*0x2."}
$sleeptype = if (!$hibernationevents -Or (New-TimeSpan -start ($hibernationevents | Select -first 1).Timecreated -end $waketime).TotalSeconds -gt 5) { "sleep" } else { "hibernation" }
$wakereason = (( % {[regex]::Match($wake.message, 'Wake Source: (.*)$')}).Groups)[1]
Write-Host $('Sleep reason: {0}, sleep type: {1}, wake reason: {2}' -f $sleepreason, $sleeptype, $wakereason)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment