Before jumping into the code:
WMI Reference
Windows Management Instrumentation (WMI) provides access to information about objects in a managed environment. This is an implementation of the Desktop Management Task Force’s (DMTF) Web Based Enterprise Management (WBEM). WMI has a query language (WQL), one can use that to query Windows Management Service.
Fine. But how I use this WMI in .NET?! Here the answer.
System.Management Namespace
System.Management Namespace provides access to a rich set of management information (such as how much free space is left on the disk, what is the current CPU utilization ….) and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure.
Here the Code:
using System.Management;
public class Win32OperatingSystem
{
public static void Shutdown(string machineName, string username, string password)
{
ManagementScope Scope = null;
ConnectionOptions ConnOptions = null;
ObjectQuery ObjQuery = null;
ManagementObjectSearcher ObjSearcher = null;
try
{
ConnOptions = new ConnectionOptions();
ConnOptions.Impersonation = ImpersonationLevel.Impersonate;
ConnOptions.EnablePrivileges = true;
if (machineName.ToUpper() == Environment.MachineName.ToUpper() )
Scope = new ManagementScope(@"\ROOT\CIMV2", ConnOptions); else
{
ConnOptions.Username = username;
ConnOptions.Password = password;
Scope = new ManagementScope(@"\\" + machineName + @"\ROOT\CIMV2", ConnOptions);
}
Scope.Connect();
ObjQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ObjSearcher = new ManagementObjectSearcher(Scope, ObjQuery );
foreach( ManagementObject operatingSystem in ObjSearcher.Get())
{
MessageBox.Show("Caption = " + operatingSystem.GetPropertyValue("Caption"));
MessageBox.Show("Version = " + operatingSystem.GetPropertyValue("Version"));
ManagementBaseObject outParams = operatingSystem.InvokeMethod ("Shutdown",null,null);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Call the function like:
[STAThread]
static void Main(string[] args)
{
Win32OperatingSystem.Shutdown(@"Machinename", @"UserName", @"Pwd");
}
1 comment:
Clear and neat
Post a Comment