You are hereC#.Net - Get Remote Computer Uptime


C#.Net - Get Remote Computer Uptime


By hagrin - Posted on 15 June 2011

Recently, at one of my jobs, the company's virtual servers were experiencing random, unnoticed reboots that would occur so quickly that their monitoring software, ManageEngine's OpManager (which does an extremely pitiful job at reporting correct uptimes by the way), wouldn't even send out a down alert. Admins were only being notified when they logged onto the box and actually saw a reboot reason message box.

Therefore, to supplement OpManager, we wanted a script/page that gave an overview of all the servers and their uptimes/last reboot. I came up with the following code which will query on a single machine -

using System.Management;

...

ManagementScope scope = new ManagementScope("\\\\COMPUTERNAME\\root\\cimv2");
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
// Display the remote computer information
// http://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx - list of available attributes
Console.WriteLine("Uptime : {0}", m["LastBootUpTime"]);
Console.WriteLine("Computer Name : {0}", m["csname"]);
}
queryCollection.Dispose();
this.Close();

You can easily put the machines you want to query in a database or an array and run this code through a loop to query the uptimes of all your machines in an organization. You can also clean up the formatting of the LastBootUptime to be more readable, but that's up to the developer.

Hope this code snippet helps someone manage their networks.