Get the server uptime in days with WMI
Get the server uptime in days with WMI

This script gets the Active Directory server uptime in days using WMI. The WMI class used is Win32_OperatingSystem

I have used the New-Timespan to calculate the uptime (difference between the current date and the last Windows boot up time).

[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)
This will compare the output time with the current time and store the result to the string as object

The property ConvertToDateTime gives a readable value contained in the variable “LastBootUpTime”.

The default display of the System.TimeSpan object is shown here:

Days              : 0
Hours             : 0
Minutes           : 40
Seconds           : 55
Milliseconds      : 914
Ticks             : 24559148010
TotalDays         : 0.0284249398263889
TotalHours        : 0.682198555833333
TotalMinutes      : 40.93191335
TotalSeconds      : 2455.914801
TotalMilliseconds : 2455914.801

The script below performs the following actions :

  • lists all servers in the Active Directory domain
  • ping each server in the list
  • if the ping is successful, get the uptime of the server calculated in days

Script :

$list = get-adcomputer -LDAPFilter "(operatingsystem=Windows*Server*)" 

foreach ($entry in $list) {
	$ad_entry = $entry.name
	$strQuery = "select * from win32_pingstatus where address = '" + $ad_entry + "'"
	$wmi = Get-WmiObject -Query $strQuery
	if ($wmi.statuscode -eq 0) {
		try{
			$Booted = Get-WmiObject -Class Win32_OperatingSystem -Computer $ad_entry -ErrorAction Stop -WarningAction Stop
			$uptime = New-TimeSpan -Start $Booted.ConvertToDateTime($Booted.LastBootUpTime) -End (Get-Date)
			$uptime_str = $uptime.Days
			Write-Host $ad_entry ";" $uptime_str
		}
		catch{Write-Host "unable to get uptime info for " $ad_entry}
	}
}

 

Cmdlet references :

Get the server uptime in days with WMI

Leave a Reply

Your email address will not be published. Required fields are marked *