Hello all, more powershell fun. How often are you trouble shooting an application install or “insert error here” and the end user says, “Yes I rebooted!!!”. Not that we don’t trust the end user, but it helps to be able to verify that the computer was rebooted. Here is a small script I use to determine the computer uptime and reboots, it will show who rebooted it and why. To load the function save and run the script. The function can be called from the PS session. This can be added to your PS profile to load when you start a PS session.
The script is made up of 2 functions. One for determining the computer uptime and the other to read the event log and report on reboots.
You can either run it on a single computer or supply a list of computers from text file with one computer per-line.
Get-rebootInfo -computername “server”
Get-Content computers.txt | ForEach-Object { Get-rebootInfo -computername $_}
#Code#
Function Get-rebootInfo {
param(
## Computers
$computername
)
#Adds a title section to the output with Date, computer ran on, and Uptime.
“#”*160
“Server Reboot Report”
“Generated $(get-date)”
“Generated from $(gc env:computername)”
“Genertaed for $Computername”
Get-Uptime $computername
“#”*160
Stores the events in a hash table for faster parsing and reporting.
Get-WinEvent -ComputerName $computername -FilterHashtable @{logname=’System’; id=1074} |
ForEach-Object {
$rv = New-Object PSObject | Select-Object Date, User, Action, Process, Reason, ReasonCode, Comment
$rv.Date = $_.TimeCreated
$rv.User = $_.Properties[6].Value
$rv.Process = $_.Properties[0].Value
$rv.Action = $_.Properties[4].Value
$rv.Reason = $_.Properties[2].Value
$rv.ReasonCode = $_.Properties[3].Value
$rv.Comment = $_.Properties[5].Value
$rv
} | Select-Object Date, Action, Reason, User
}
#function used to get LastBootUpTime from Win32_OperatingSystem class and calculate uptime based on the local system time.
Function Get-Uptime {
Param([Parameter(Mandatory = $True,
ValueFromPipeLine = $False,
Position = 0)]
[Alias(”)]
[String]$ComputerName = “localhost”
)#END: Param
$LastBoot = (Get-WmiObject -Class Win32_OperatingSystem `
-computername $ComputerName).LastBootUpTime
$sysuptime = (Get-Date) – `
[System.Management.ManagementDateTimeconverter]::`
ToDateTime($LastBoot)
Write-Host -foregroundcolor cyan “($ComputerName) System uptime is:” `
$sysuptime.days”days”$sysuptime.hours”hours”$sysuptime.minutes`
“minutes”$sysuptime.seconds”seconds”
}#End Function Get-Uptime