1.WMI简介
WMI是英文WindowsManagementInstrumentation的简写,通过使用WMI,我们可以获取本地或远程服务器的性能参数和进程运行情况,以及大部分硬件信息,但前提是运行的用户要有足够的权限,如administrator组用户等。这也是做负载均衡所需要且比较方便快捷的途径。
2.使用时首先添加System.Management.dll,然后引用
usingSystem.Management;
3.定义远程访问
publicclassManagementConnectPool
...{
privatestaticSystem.Management.ConnectionOptionsConn=newConnectionOptions();
privatestaticManagementObjectSearchermos=newManagementObjectSearcher();
privatestringusername="";
privatestringpwd="";
privatestringspace="";
privatestringserver="";
publicManagementConnectPool(stringmpusername,stringmppwd,stringmpspace,stringmpserver)
...{
this.username=mpusername;
this.pwd=mppwd;
this.space=mpspace;
this.server=mpserver;
Conn.Username=mpusername;
Conn.Password=mppwd;
stringscopestring="//"+mpserver+mpspace;
System.Management.ManagementScopeMs=newManagementScope(scopestring);
Ms.Connect();
mos.Scope=Ms;
}
publicManagementObjectCollectiongetQueryResult(stringqueryString)
...{
ObjectQueryoq=newObjectQuery();
oq.QueryString=queryString;
mos.Query=oq;
ManagementObjectCollectionmoc=mos.Get();
returnmoc;
}
}
4.获取CPU,内存,网络流量等信息
publicclassMonitor
...{
privatestringusername="";
privatestringpwd="";
privatestringip="";
ManagementConnectPoolmcp;
WMSServerClassserver;
publicMonitor(stringusername,stringpwd,stringip)...{
this.username=username;
this.pwd=pwd;
this.ip=ip;
mcp=newManagementConnectPool(username,pwd,"/root/cimv2",ip);
server=newWMSServerClass();
}
WMI方式获取网卡流量#regionWMI方式获取网卡流量
privatevoidgetNetWorkFlow()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult(@"select*fromWin32_NetworkAdapterwheremacaddress<>nullandmanufacturer<>'Microsoft'");
string[]list=newstring[moc.Count];
foreach(System.Management.ManagementObjectmymacinmoc)
...{
stringa=mymac["Speed"].ToString();//nullWMI未实现该属性
Console.WriteLine(a.ToString());
}
}
#endregion
WMI方式获取CPU信息#regionWMI方式获取CPU信息
privatevoidgetCpuInfo()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult("select*fromWin32_Processor");
string[]list=newstring[moc.Count];
inti=0;
foreach(ManagementObjectmoinmoc)
...{
stringtotal=mo.GetPropertyValue("LoadPercentage").ToString();
list[i]=total;
i++;
}
}
#endregion
WMI方式获取内存使用率#regionWMI方式获取内存使用率
publicstringgetMemoryUsage()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult("select*fromWin32_LogicalMemoryConfiguration");
inttotalm=1;intavilablem=1;
foreach(ManagementObjectmoinmoc)
...{
stringtotal=mo.GetPropertyValue("TotalPhysicalMemory").ToString();
totalm=int.Parse(total);
}
moc=mcp.getQueryResult("select*fromWin32_PerfRawData_PerfOS_Memory");
foreach(ManagementObjectmoinmoc)
...{
stringavilable=mo.GetPropertyValue("AvailableKBytes").ToString();
avilablem=int.Parse(avilable);
}
intusedm=totalm-avilablem;
doublememoryusage=(double)usedm*(double)100/(double)totalm;
returnmemoryusage.ToString();
}
#endregion
}
5.获取本地机器信息(WEB)
1.如何用WMI获得指定磁盘的容量#region1.如何用WMI获得指定磁盘的容量
privatestringDriveType(stringtype)
...{
stringrtntype="";
switch(type)
...{
case"1":
rtntype="NotType";
break;
case"2":
rtntype="Floppydisk";
break;
case"3":
rtntype="Harddisk";
break;
case"4":
rtntype="Removabledriveornetworkdrive";
break;
case"5":
rtntype="CD-ROM";
break;
case"6":
rtntype="RAMdisk";
break;
default:
break;
}
returnrtntype;
}
privatevoidButton1_Click(objectsender,System.EventArgse)
...{
SelectQueryquery=newSelectQuery("Select*FromWin32_LogicalDisk");
ManagementObjectSearchersearcher=newManagementObjectSearcher(query);
foreach(ManagementBaseObjectdiskinsearcher.Get())
...{
Response.Write(disk["Name"]+""+DriveType(disk["DriveType"].ToString())+""+disk["VolumeName"]+"<br>");
}
}
#endregion
2.如何用WMI获得指定磁盘的容量#region2.如何用WMI获得指定磁盘的容量
privatevoidButton2_Click(objectsender,System.EventArgse)
...{
ManagementObjectdisk=newManagementObject("win32_logicaldisk.deviceid="c:"");
disk.Get();
Response.Write("LogicalDiskSize="+disk["Size"]+"bytes");
}
#endregion
3.如何列出机器中所有的共享资源#region3.如何列出机器中所有的共享资源
privatevoidButton3_Click(objectsender,System.EventArgse)
...{
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_share");
foreach(ManagementObjectshareinsearcher.Get())
...{
Response.Write(share.GetText(TextFormat.Mof));
}
}
#endregion
4.怎样写程控制让系统中的某个文件夹共享或取消共享#region4.怎样写程控制让系统中的某个文件夹共享或取消共享
privatevoidButton4_Click(objectsender,System.EventArgse)
...{
/**//*首先,这需要以有相应权限的用户登录系统才行
将
object[]obj={"C:/Temp","我的共享",0,10,"DotNet实现的共享",""};
改为
object[]obj={"C:/Temp","我的共享",0,null,"DotNet实现的共享",""};
就可以实现授权给最多用户了。
*/
ManagementClass_class=newManagementClass(newManagementPath("Win32_Share"));
object[]obj=...{"C:/Temp","我的共享",0,10,"DotNet实现的共享",""};
_class.InvokeMethod("create",obj);
}
#endregion
5.如何获得系统服务的运行状态#region5.如何获得系统服务的运行状态
privatevoidButton5_Click(objectsender,System.EventArgse)
...{
string[]lvData=newstring[4];
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_Service");
foreach(ManagementObjectmoinsearcher.Get())
...{
lvData[0]=mo["Name"].ToString();
lvData[1]=mo["StartMode"].ToString();
if(mo["Started"].Equals(true))
lvData[2]="Started";
else
lvData[2]="Stop";
lvData[3]=mo["StartName"].ToString();
Response.Write(lvData[0]+lvData[1]+lvData[2]+lvData[3]);
}
}
#endregion
6.通过WMI修改IP,而实现不用重新启动#region6.通过WMI修改IP,而实现不用重新启动
privatevoidButton6_Click(objectsender,System.EventArgse)
...{
ReportIP();
//SwitchToDHCP();
SwitchToprivate();
Thread.Sleep(5000);
ReportIP();
Response.Write("end.");
}
privatevoidSwitchToDHCP()
...{
ManagementBaseObjectinPar=null;
ManagementBaseObjectoutPar=null;
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
inPar=mo.GetMethodParameters("EnableDHCP");
outPar=mo.InvokeMethod("EnableDHCP",inPar,null);
break;
}
}
privatevoidSwitchToprivate()
...{
ManagementBaseObjectinPar=null;
ManagementBaseObjectoutPar=null;
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
inPar=mo.GetMethodParameters("Enableprivate");
inPar["IPAddress"]=newstring[]...{"192.168.1.1"};
inPar["SubnetMask"]=newstring[]...{"255.255.255.0"};
outPar=mo.InvokeMethod("Enableprivate",inPar,null);
break;
}
}
privatevoidReportIP()
...{
Response.Write("******CurrentIPaddresses:");
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
stringstr="{0} SVC:'{1}'MAC:[{2}]";
str=string.Format(mo["Caption"].ToString(),mo["ServiceName"].ToString(),mo["MACAddress"].ToString());
Response.Write(str);
string[]addresses=(string[])mo["IPAddress"];
string[]subnets=(string[])mo["IPSubnet"];
Response.Write("Addresses:");
foreach(stringsadinaddresses)
Response.Write(sad+"<br>");
Response.Write("Subnets:");
foreach(stringsubinsubnets)
Response.Write(sub+"<br>");
}
}
#endregion
7.如何利用WMI远程重启远程计算机#region7.如何利用WMI远程重启远程计算机
privatevoidButton7_Click(objectsender,System.EventArgse)
...{
Response.Write("ComputerdetailsretrievedusingWindowsManagementInstrumentation(WMI)");
Response.Write("mailto:singlepine@hotmail.com");
Response.Write("=========================================================================");
//连接远程计算机
ConnectionOptionsco=newConnectionOptions();
co.Username="john";
co.Password="john";
System.Management.ManagementScopems=newSystem.Management.ManagementScope("//192.168.1.2/root/cimv2",co);
//查询远程计算机
System.Management.ObjectQueryoq=newSystem.Management.ObjectQuery("SELECT*FROMWin32_OperatingSystem");
ManagementObjectSearcherquery1=newManagementObjectSearcher(ms,oq);
ManagementObjectCollectionqueryCollection1=query1.Get();
foreach(ManagementObjectmoinqueryCollection1)
...{
string[]ss=...{""};
mo.InvokeMethod("Reboot",ss);
Response.Write(mo.ToString());
}
}
#endregion
8.利用WMI创建一个新的进程#region8.利用WMI创建一个新的进程
privatevoidButton8_Click(objectsender,System.EventArgse)
...{
//Gettheobjectonwhichthemethodwillbeinvoked
ManagementClassprocessClass=newManagementClass("Win32_Process");
//Getaninputparametersobjectforthismethod
ManagementBaseObjectinParams=processClass.GetMethodParameters("Create");
//Fillininputparametervalues
inParams["CommandLine"]="calc.exe";
//Executethemethod
ManagementBaseObjectoutParams=processClass.InvokeMethod("Create",inParams,null);
//Displayresults
//Note:Thereturncodeofthemethodisprovidedinthe"returnvalue"propertyoftheoutParamsobject
Response.Write("Creationofcalculatorprocessreturned:"+outParams["returnvalue"]);
Response.Write("ProcessID:"+outParams["processId"]);
}
#endregion
9.如何通过WMI终止一个进程#region9.如何通过WMI终止一个进程
privatevoidButton9_Click(objectsender,System.EventArgse)
...{
ManagementObjectservice=
newManagementObject("win32_service="winmgmt"");
InvokeMethodOptionsoptions=newInvokeMethodOptions();
options.Timeout=newTimeSpan(0,0,0,5);
ManagementBaseObjectoutParams=service.InvokeMethod("StopService",null,options);
Response.Write("ReturnStatus="+outParams["Returnvalue"]);
}
#endregion
10.如何用WMI来获取远程机器的目录以及文件#region10.如何用WMI来获取远程机器的目录以及文件
privatevoidButton10_Click(objectsender,System.EventArgse)
...{
ManagementObjectdisk=newManagementObject(
"win32_logicaldisk.deviceid="c:"");
disk.Get();
Response.Write("LogicalDiskSize="+disk["Size"]+"bytes");
}
#endregion
11.网卡的MAC地址#region11.网卡的MAC地址
privatevoidButton11_Click(objectsender,System.EventArgse)
...{
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if((bool)mo["IPEnabled"]==true)
Response.Write("MACaddress"+mo["MacAddress"].ToString()+"<br>");
mo.Dispose();
}
}
#endregion
12.CPU的系列号#region12.CPU的系列号
privatevoidButton12_Click(objectsender,System.EventArgse)
...{
stringcpuInfo="";//cpu序列号
ManagementClasscimobject=newManagementClass("Win32_Processor");
ManagementObjectCollectionmoc=cimobject.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
cpuInfo=mo.Properties["ProcessorId"].Value.ToString();
Response.Write(cpuInfo);
}
}
#endregion
13.主板的系列号#region13.主板的系列号
privatevoidButton13_Click(objectsender,System.EventArgse)
...{
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_BaseBoard");
foreach(ManagementObjectshareinsearcher.Get())
...{
Response.Write("主板制造商:"+share["Manufacturer"].ToString());
Response.Write("型号:"+share["Product"].ToString());
Response.Write("序列号:"+share["SerialNumber"].ToString());
}
}
#endregion
14.获取硬盘ID#region14.获取硬盘ID
privatevoidButton14_Click(objectsender,System.EventArgse)
...{
StringHDid;
ManagementClasscimobject=newManagementClass("Win32_DiskDrive");
ManagementObjectCollectionmoc=cimobject.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
HDid=(string)mo.Properties["Model"].Value;
Response.Write(HDid);
}
}
#endregion
15.获取本机的用户列表#region15.获取本机的用户列表
privatevoidButton15_Click(objectsender,System.EventArgse)
...{
SelectQueryquery=newSelectQuery("SELECT*FROMWin32_UserAccount");
ManagementObjectSearchersearcher=newManagementObjectSearcher(query);
foreach(ManagementObjectosinsearcher.Get())
...{
Response.Write(os["Name"]);
}
}
#endregion
}
通过上面介绍的方法,可以很轻松的获取远程或本地机器的性能,进程和硬件信息等。另外:WMI也可以通过使用Vbscript等脚本调用。
说明:其中部分资源来自网友小山的blog。但不够详细说明WMI在服务器性能方面的能力!
1.WMI简介
WMI是英文WindowsManagementInstrumentation的简写,通过使用WMI,我们可以获取本地或远程服务器的性能参数和进程运行情况,以及大部分硬件信息,但前提是运行的用户要有足够的权限,如administrator组用户等。这也是做负载均衡所需要且比较方便快捷的途径。
2.使用时首先添加System.Management.dll,然后引用
usingSystem.Management;
3.定义远程访问
publicclassManagementConnectPool
...{
privatestaticSystem.Management.ConnectionOptionsConn=newConnectionOptions();
privatestaticManagementObjectSearchermos=newManagementObjectSearcher();
privatestringusername="";
privatestringpwd="";
privatestringspace="";
privatestringserver="";
publicManagementConnectPool(stringmpusername,stringmppwd,stringmpspace,stringmpserver)
...{
this.username=mpusername;
this.pwd=mppwd;
this.space=mpspace;
this.server=mpserver;
Conn.Username=mpusername;
Conn.Password=mppwd;
stringscopestring="//"+mpserver+mpspace;
System.Management.ManagementScopeMs=newManagementScope(scopestring);
Ms.Connect();
mos.Scope=Ms;
}
publicManagementObjectCollectiongetQueryResult(stringqueryString)
...{
ObjectQueryoq=newObjectQuery();
oq.QueryString=queryString;
mos.Query=oq;
ManagementObjectCollectionmoc=mos.Get();
returnmoc;
}
}
4.获取CPU,内存,网络流量等信息
publicclassMonitor
...{
privatestringusername="";
privatestringpwd="";
privatestringip="";
ManagementConnectPoolmcp;
WMSServerClassserver;
publicMonitor(stringusername,stringpwd,stringip)...{
this.username=username;
this.pwd=pwd;
this.ip=ip;
mcp=newManagementConnectPool(username,pwd,"/root/cimv2",ip);
server=newWMSServerClass();
}
WMI方式获取网卡流量#regionWMI方式获取网卡流量
privatevoidgetNetWorkFlow()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult(@"select*fromWin32_NetworkAdapterwheremacaddress<>nullandmanufacturer<>'Microsoft'");
string[]list=newstring[moc.Count];
foreach(System.Management.ManagementObjectmymacinmoc)
...{
stringa=mymac["Speed"].ToString();//nullWMI未实现该属性
Console.WriteLine(a.ToString());
}
}
#endregion
WMI方式获取CPU信息#regionWMI方式获取CPU信息
privatevoidgetCpuInfo()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult("select*fromWin32_Processor");
string[]list=newstring[moc.Count];
inti=0;
foreach(ManagementObjectmoinmoc)
...{
stringtotal=mo.GetPropertyValue("LoadPercentage").ToString();
list[i]=total;
i++;
}
}
#endregion
WMI方式获取内存使用率#regionWMI方式获取内存使用率
publicstringgetMemoryUsage()
...{
ManagementObjectCollectionmoc=mcp.getQueryResult("select*fromWin32_LogicalMemoryConfiguration");
inttotalm=1;intavilablem=1;
foreach(ManagementObjectmoinmoc)
...{
stringtotal=mo.GetPropertyValue("TotalPhysicalMemory").ToString();
totalm=int.Parse(total);
}
moc=mcp.getQueryResult("select*fromWin32_PerfRawData_PerfOS_Memory");
foreach(ManagementObjectmoinmoc)
...{
stringavilable=mo.GetPropertyValue("AvailableKBytes").ToString();
avilablem=int.Parse(avilable);
}
intusedm=totalm-avilablem;
doublememoryusage=(double)usedm*(double)100/(double)totalm;
returnmemoryusage.ToString();
}
#endregion
}
5.获取本地机器信息(WEB)
1.如何用WMI获得指定磁盘的容量#region1.如何用WMI获得指定磁盘的容量
privatestringDriveType(stringtype)
...{
stringrtntype="";
switch(type)
...{
case"1":
rtntype="NotType";
break;
case"2":
rtntype="Floppydisk";
break;
case"3":
rtntype="Harddisk";
break;
case"4":
rtntype="Removabledriveornetworkdrive";
break;
case"5":
rtntype="CD-ROM";
break;
case"6":
rtntype="RAMdisk";
break;
default:
break;
}
returnrtntype;
}
privatevoidButton1_Click(objectsender,System.EventArgse)
...{
SelectQueryquery=newSelectQuery("Select*FromWin32_LogicalDisk");
ManagementObjectSearchersearcher=newManagementObjectSearcher(query);
foreach(ManagementBaseObjectdiskinsearcher.Get())
...{
Response.Write(disk["Name"]+""+DriveType(disk["DriveType"].ToString())+""+disk["VolumeName"]+"<br>");
}
}
#endregion
2.如何用WMI获得指定磁盘的容量#region2.如何用WMI获得指定磁盘的容量
privatevoidButton2_Click(objectsender,System.EventArgse)
...{
ManagementObjectdisk=newManagementObject("win32_logicaldisk.deviceid="c:"");
disk.Get();
Response.Write("LogicalDiskSize="+disk["Size"]+"bytes");
}
#endregion
3.如何列出机器中所有的共享资源#region3.如何列出机器中所有的共享资源
privatevoidButton3_Click(objectsender,System.EventArgse)
...{
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_share");
foreach(ManagementObjectshareinsearcher.Get())
...{
Response.Write(share.GetText(TextFormat.Mof));
}
}
#endregion
4.怎样写程控制让系统中的某个文件夹共享或取消共享#region4.怎样写程控制让系统中的某个文件夹共享或取消共享
privatevoidButton4_Click(objectsender,System.EventArgse)
...{
/**//*首先,这需要以有相应权限的用户登录系统才行
将
object[]obj={"C:/Temp","我的共享",0,10,"DotNet实现的共享",""};
改为
object[]obj={"C:/Temp","我的共享",0,null,"DotNet实现的共享",""};
就可以实现授权给最多用户了。
*/
ManagementClass_class=newManagementClass(newManagementPath("Win32_Share"));
object[]obj=...{"C:/Temp","我的共享",0,10,"DotNet实现的共享",""};
_class.InvokeMethod("create",obj);
}
#endregion
5.如何获得系统服务的运行状态#region5.如何获得系统服务的运行状态
privatevoidButton5_Click(objectsender,System.EventArgse)
...{
string[]lvData=newstring[4];
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_Service");
foreach(ManagementObjectmoinsearcher.Get())
...{
lvData[0]=mo["Name"].ToString();
lvData[1]=mo["StartMode"].ToString();
if(mo["Started"].Equals(true))
lvData[2]="Started";
else
lvData[2]="Stop";
lvData[3]=mo["StartName"].ToString();
Response.Write(lvData[0]+lvData[1]+lvData[2]+lvData[3]);
}
}
#endregion
6.通过WMI修改IP,而实现不用重新启动#region6.通过WMI修改IP,而实现不用重新启动
privatevoidButton6_Click(objectsender,System.EventArgse)
...{
ReportIP();
//SwitchToDHCP();
SwitchToprivate();
Thread.Sleep(5000);
ReportIP();
Response.Write("end.");
}
privatevoidSwitchToDHCP()
...{
ManagementBaseObjectinPar=null;
ManagementBaseObjectoutPar=null;
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
inPar=mo.GetMethodParameters("EnableDHCP");
outPar=mo.InvokeMethod("EnableDHCP",inPar,null);
break;
}
}
privatevoidSwitchToprivate()
...{
ManagementBaseObjectinPar=null;
ManagementBaseObjectoutPar=null;
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
inPar=mo.GetMethodParameters("Enableprivate");
inPar["IPAddress"]=newstring[]...{"192.168.1.1"};
inPar["SubnetMask"]=newstring[]...{"255.255.255.0"};
outPar=mo.InvokeMethod("Enableprivate",inPar,null);
break;
}
}
privatevoidReportIP()
...{
Response.Write("******CurrentIPaddresses:");
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
stringstr="{0} SVC:'{1}'MAC:[{2}]";
str=string.Format(mo["Caption"].ToString(),mo["ServiceName"].ToString(),mo["MACAddress"].ToString());
Response.Write(str);
string[]addresses=(string[])mo["IPAddress"];
string[]subnets=(string[])mo["IPSubnet"];
Response.Write("Addresses:");
foreach(stringsadinaddresses)
Response.Write(sad+"<br>");
Response.Write("Subnets:");
foreach(stringsubinsubnets)
Response.Write(sub+"<br>");
}
}
#endregion
7.如何利用WMI远程重启远程计算机#region7.如何利用WMI远程重启远程计算机
privatevoidButton7_Click(objectsender,System.EventArgse)
...{
Response.Write("ComputerdetailsretrievedusingWindowsManagementInstrumentation(WMI)");
Response.Write("mailto:singlepine@hotmail.com");
Response.Write("=========================================================================");
//连接远程计算机
ConnectionOptionsco=newConnectionOptions();
co.Username="john";
co.Password="john";
System.Management.ManagementScopems=newSystem.Management.ManagementScope("//192.168.1.2/root/cimv2",co);
//查询远程计算机
System.Management.ObjectQueryoq=newSystem.Management.ObjectQuery("SELECT*FROMWin32_OperatingSystem");
ManagementObjectSearcherquery1=newManagementObjectSearcher(ms,oq);
ManagementObjectCollectionqueryCollection1=query1.Get();
foreach(ManagementObjectmoinqueryCollection1)
...{
string[]ss=...{""};
mo.InvokeMethod("Reboot",ss);
Response.Write(mo.ToString());
}
}
#endregion
8.利用WMI创建一个新的进程#region8.利用WMI创建一个新的进程
privatevoidButton8_Click(objectsender,System.EventArgse)
...{
//Gettheobjectonwhichthemethodwillbeinvoked
ManagementClassprocessClass=newManagementClass("Win32_Process");
//Getaninputparametersobjectforthismethod
ManagementBaseObjectinParams=processClass.GetMethodParameters("Create");
//Fillininputparametervalues
inParams["CommandLine"]="calc.exe";
//Executethemethod
ManagementBaseObjectoutParams=processClass.InvokeMethod("Create",inParams,null);
//Displayresults
//Note:Thereturncodeofthemethodisprovidedinthe"returnvalue"propertyoftheoutParamsobject
Response.Write("Creationofcalculatorprocessreturned:"+outParams["returnvalue"]);
Response.Write("ProcessID:"+outParams["processId"]);
}
#endregion
9.如何通过WMI终止一个进程#region9.如何通过WMI终止一个进程
privatevoidButton9_Click(objectsender,System.EventArgse)
...{
ManagementObjectservice=
newManagementObject("win32_service="winmgmt"");
InvokeMethodOptionsoptions=newInvokeMethodOptions();
options.Timeout=newTimeSpan(0,0,0,5);
ManagementBaseObjectoutParams=service.InvokeMethod("StopService",null,options);
Response.Write("ReturnStatus="+outParams["Returnvalue"]);
}
#endregion
10.如何用WMI来获取远程机器的目录以及文件#region10.如何用WMI来获取远程机器的目录以及文件
privatevoidButton10_Click(objectsender,System.EventArgse)
...{
ManagementObjectdisk=newManagementObject(
"win32_logicaldisk.deviceid="c:"");
disk.Get();
Response.Write("LogicalDiskSize="+disk["Size"]+"bytes");
}
#endregion
11.网卡的MAC地址#region11.网卡的MAC地址
privatevoidButton11_Click(objectsender,System.EventArgse)
...{
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if((bool)mo["IPEnabled"]==true)
Response.Write("MACaddress"+mo["MacAddress"].ToString()+"<br>");
mo.Dispose();
}
}
#endregion
12.CPU的系列号#region12.CPU的系列号
privatevoidButton12_Click(objectsender,System.EventArgse)
...{
stringcpuInfo="";//cpu序列号
ManagementClasscimobject=newManagementClass("Win32_Processor");
ManagementObjectCollectionmoc=cimobject.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
cpuInfo=mo.Properties["ProcessorId"].Value.ToString();
Response.Write(cpuInfo);
}
}
#endregion
13.主板的系列号#region13.主板的系列号
privatevoidButton13_Click(objectsender,System.EventArgse)
...{
ManagementObjectSearchersearcher=newManagementObjectSearcher("SELECT*FROMWin32_BaseBoard");
foreach(ManagementObjectshareinsearcher.Get())
...{
Response.Write("主板制造商:"+share["Manufacturer"].ToString());
Response.Write("型号:"+share["Product"].ToString());
Response.Write("序列号:"+share["SerialNumber"].ToString());
}
}
#endregion
14.获取硬盘ID#region14.获取硬盘ID
privatevoidButton14_Click(objectsender,System.EventArgse)
...{
StringHDid;
ManagementClasscimobject=newManagementClass("Win32_DiskDrive");
ManagementObjectCollectionmoc=cimobject.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
HDid=(string)mo.Properties["Model"].Value;
Response.Write(HDid);
}
}
#endregion
15.获取本机的用户列表#region15.获取本机的用户列表
privatevoidButton15_Click(objectsender,System.EventArgse)
...{
SelectQueryquery=newSelectQuery("SELECT*FROMWin32_UserAccount");
ManagementObjectSearchersearcher=newManagementObjectSearcher(query);
foreach(ManagementObjectosinsearcher.Get())
...{
Response.Write(os["Name"]);
}
}
#endregion
}
通过上面介绍的方法,可以很轻松的获取远程或本地机器的性能,进程和硬件信息等。另外:WMI也可以通过使用Vbscript等脚本调用。
说明:其中部分资源来自网友小山的blog。但不够详细说明WMI在服务器性能方面的能力!