Powershell; Dynamic System Uptime Report for Windows Servers and or Workstations

After you’ve cranked out a few reports in PowerShell, either you or your boss will eventually wonder if it can be used to create an uptime report. A quick search of the Internet will return lots of options for calculating the uptime by subtracting the lastboottime, obtained via WMI, from the current date. This technique works well but few if any of the articles suggest how you go about creating a report that shows the information for all of your Windows Servers.

I tried a handful of the scripts I found on-line and didn’t like the results so I decided to write my own. The code below will scan your window’s domains and locate a domain controller in each. It will contact those domain controllers and scan for computer objects whose operating system contains the words “Windows Server”. Next it will connect to each of those computers and use WMI to calculate the uptime. Finally it will create a report showing each server’s Name, Operating System, and Up Time.

It would be simple to have the report scan workstations instead. Just change the word “Server” to “Workstation”, you could also add an and statement to do both. Emailing the report would be cinch as well (Search for PowerShell SendMail) and the script already written in a manner that would support running it as a scheduled task.


Import-Module ActiveDirectory
$domains = (Get-ADForest).domains
$dcs = Foreach ($domain in $domains) {Get-ADDomainController -DomainName $domain -Discover -Service PrimaryDC}
$servers = Foreach ($dc in $dcs) {
Get-ADComputer -Properties * -Filter {(OperatingSystem -like "*Windows Server*")}|Select DNSHostName -ExpandProperty DNSHostName

$report = @()

Foreach ($Server in $Servers) {
$wmi = Get-WMIObject -Class Win32_OperatingSystem -ComputerName $Server
$lastboottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
$sysuptime = (Get-Date) - $lastboottime
$uptime = "$($sysuptime.days) Days, $($sysuptime.hours) Hours, $($sysuptime.minutes) Minutes, $($sysuptime.seconds) Seconds"
$Report += $wmi | select @{n="Server";e={$_.CSName}}, @{n="Operating System";e={$_.Caption}}, @{n="System Uptime";e={$uptime}}
$Report|Export-CSV $env:userprofile\documents\Windows_Server_Uptime_Report.csv -notypeinformation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s