65.9K
CodeProject is changing. Read more.
Home

Fetch reboot time of remote servers

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Sep 6, 2012

CPOL

1 min read

viewsIcon

12941

Test whether your remote server rebooted or not from C# code.

Introduction

This article explains how to test from C# code whether your remote server or personal computer rebooted or not and get the last reboot time. Without logging into a machine we can get the last reboot time of machine from C# code.

Background

I am supporting some remote servers and patches will be installed on these regularly. To maintain the avalability of these servers I need to check the last reboot time, and for this I need to log on to the server manually to get the reboot time by running the below command on CMD.

SYSTEMINFO | FIND " Up Time"

This takes a lot of time, to log on to the machine and get this.

Using the code

The System.Management class provides us sytem information of remote machines by creating an object as follows.

After creating the ManagementScope object, use this and create a ProcessClass object and call the GetInstances() function, and get the Last Reboot Time property of the machine. Like this we can get the processor speed and hardware capacity.

ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Username = userName;
connOptions.Password = password;
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope;

try
{
  manScope= new ManagementScope(string.Format(@"\\{0}\ROOT\CIMV2", 
                serverName), connOptions);
  manScope.Connect();
}

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_OperatingSystem");
ManagementClass processClass = new ManagementClass(manScope, 
                managementPath, objectGetOptions);

foreach (ManagementObject item in processClass.GetInstances())
{
    datetime = item["LastBootUpTime"].ToString();
}

Points of Interest

From this I learnt how to access machine information from C# using the class System.Management.ManagementScope. I am now preparing a UI thing for easy usage of the code.

Fetch reboot time of remote servers - CodeProject