16 March 2022

Last Server Reboot Reporting

Recently, we needed a report of the last boot time of all servers. I wrote this PowerShell script that queries AD for a list of all windows servers and then does a WMI query on each server for the LastBootUpTime. It then calculates the number of days and writes this to an object with the computer name and the number of days since the last reboot. It will write this info to a CSV file. 

You can download the script from my GitHub site.

 Import-Module -Name ActiveDirectory -Force  
 #Get list of windows based servers  
 $Servers = Get-ADComputer -Filter * -Properties * | Where-Object {$_.OperatingSystem -like '*windows server*'} | Select Name | Sort-Object -Property Name  
 #Create Report Array  
 $Report = @()  
 #Parse through server list  
 Foreach ($Server in $Servers) {  
   #Get the computer name  
   $ComputerName = ([String]$Server).Split("=")[1].Split("}")[0].Trim()  
   #Check if the system is online  
   If ((Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) -eq $true) {  
     #Query last bootup time and use $Null if unobtainable  
     Try {  
       $LastBootTime = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName $ComputerName -ErrorAction SilentlyContinue).LastBootUpTime  
       $LastBoot = (New-TimeSpan -Start $LastBootTime -End (Get-Date)).Days  
     } Catch {  
       $LastBoot = $null  
     }  
     #Add computername and last boot time to the object  
     If ($ComputerName -ne $null) {  
       $SystemObject = New-Object -TypeName psobject  
       $SystemObject | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName  
       $SystemObject | Add-Member -MemberType NoteProperty -Name DaysSinceLastBoot -Value $LastBoot  
       $Report += $SystemObject  
     }  
   } else {  
       $SystemObject = New-Object -TypeName psobject  
       $SystemObject | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName  
       $SystemObject | Add-Member -MemberType NoteProperty -Name DaysSinceLastBoot -Value 'OFFLINE'  
       $Report += $SystemObject  
   }  
   $ComputerName = $null  
 }  
 #Print report to screen  
 $Report  
 $OutFile = "C:\Users\Desktop\LastRebootReport.csv"  
 #Delete CSV file if it already exists  
 If ((Test-Path -Path $OutFile) -eq $true) {  
   Remove-Item -Path $OutFile -Force  
 }  
 #Export report to CSV file  
 $Report | Export-Csv -Path $OutFile -NoClobber -Encoding UTF8 -NoTypeInformation -Force  
   

0 comments:

Post a Comment