转载:http://singlepine.cnblogs.com/articles/299457.html

1.WMI简介 WMI是英文Windows Management Instrumentation的简写,它的功能主要是:访问本地主机的一些信息和服务,可以管理远程计算机(当然你必须要拥有足够的权限),比如:重启,关机,关闭进程,创建进程等。 2.使用时首先添加System.Management.dll,然后引用

using System.Management; using System.Threading; 

3.示例代码

        #region 1.如何用WMI获得指定磁盘的容量
private string DriveType(string type)
{
string rtntype="";
switch (type)
{
case "":
rtntype="Not Type";
break;
case "":
rtntype="Floppy disk";
break;
case "":
rtntype="Hard disk";
break;
case "":
rtntype="Removable drive or network drive";
break;
case "":
rtntype="CD-ROM";
break;
case "":
rtntype="RAM disk";
break;
default :
break;
}
return rtntype;
} private void Button1_Click(object sender, System.EventArgs e)
{
SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");
ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);
foreach(ManagementBaseObject disk in searcher.Get())
{
Response.Write(disk["Name"] +" "+DriveType(disk["DriveType"].ToString()) + " " + disk["VolumeName"]+"<br>");
}
}
#endregion #region 2.如何用WMI获得指定磁盘的容量
private void Button2_Click(object sender, System.EventArgs e)
{
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
}
#endregion #region 3.如何列出机器中所有的共享资源
private void Button3_Click(object sender, System.EventArgs e)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");
foreach (ManagementObject share in searcher.Get())
{
Response.Write(share.GetText(TextFormat.Mof));
}
}
#endregion #region 4.怎样写程控制让系统中的某个文件夹共享或取消共享
private void Button4_Click(object sender, System.EventArgs e)
{
/*首先,这需要以有相应权限的用户登录系统才行

object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};
改为
object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""};
就可以实现授权给最多用户了。
*/
ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
object[] obj = {"C:\\Temp","我的共享",,,"Dot Net 实现的共享",""};
_class.InvokeMethod("create",obj);
}
#endregion #region 5.如何获得系统服务的运行状态
private void Button5_Click(object sender, System.EventArgs e)
{
string[] lvData = new string[];
ManagementObjectSearcher searcher =new ManagementObjectSearcher("SELECT * FROM Win32_Service");
foreach (ManagementObject mo in searcher.Get())
{
lvData[] = mo["Name"].ToString();
lvData[] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
lvData[] = "Started";
else
lvData[] = "Stop";
lvData[] = mo["StartName"].ToString();
Response.Write(lvData[]+lvData[]+lvData[]+lvData[]);
}
}
#endregion #region 6.通过WMI修改IP,而实现不用重新启动
private void Button6_Click(object sender, System.EventArgs e)
{
ReportIP();
// SwitchToDHCP();
SwitchToprivate();
Thread.Sleep( );
ReportIP();
Response.Write( "end." );
} private void SwitchToDHCP()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue; inPar = mo.GetMethodParameters("EnableDHCP");
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
} private void SwitchToprivate()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue; inPar = mo.GetMethodParameters( "Enableprivate" );
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "Enableprivate", inPar, null );
break;
}
} private void ReportIP()
{
Response.Write( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue; string str="{0}\n 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(string sad in addresses)
Response.Write(sad+"<br>"); Response.Write( " Subnets :" );
foreach(string sub in subnets )
Response.Write(sub+"<br>");
}
}
#endregion #region 7.如何利用WMI远程重启远程计算机
private void Button7_Click(object sender, System.EventArgs e)
{
Response.Write("Computer details retrieved using Windows Management Instrumentation (WMI)");
Response.Write("mailto:singlepine@hotmail.com");
Response.Write("=========================================================================");
//连接远程计算机
ConnectionOptions co = new ConnectionOptions();
co.Username = "john";
co.Password = "john";
System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.1.2\\root\\cimv2", co);
//查询远程计算机
System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection1 = query1.Get();
foreach( ManagementObject mo in queryCollection1 )
{
string[] ss={""};
mo.InvokeMethod("Reboot",ss);
Response.Write(mo.ToString());
}
}
#endregion #region 8.利用WMI创建一个新的进程
private void Button8_Click(object sender, System.EventArgs e)
{
//Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass("Win32_Process"); //Get an input parameters object for this method
ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); //Fill in input parameter values
inParams["CommandLine"] = "calc.exe"; //Execute the method
ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null); //Display results
//Note: The return code of the method is provided in the "returnvalue" property of the outParams object
Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]);
Response.Write("Process ID: " + outParams["processId"]); }
#endregion #region 9.如何通过WMI终止一个进程
private void Button9_Click(object sender, System.EventArgs e)
{
ManagementObject service =
new ManagementObject("win32_service=\"winmgmt\"");
InvokeMethodOptions options = new InvokeMethodOptions();
options.Timeout = new TimeSpan(,,,); ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options); Response.Write("Return Status = " + outParams["Returnvalue"]);
}
#endregion #region 10.如何用WMI 来获取远程机器的目录以及文件
private void Button10_Click(object sender, System.EventArgs e)
{
ManagementObject disk = new ManagementObject( "win32_logicaldisk.deviceid=\"c:\""); disk.Get(); Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
}
#endregion #region 11.网卡的MAC地址
private void Button11_Click(object sender, System.EventArgs e)
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if((bool)mo["IPEnabled"] == true)
Response.Write("MAC address"+mo["MacAddress"].ToString()+"<br>");
mo.Dispose();
}
}
#endregion #region 12.CPU的系列号
private void Button12_Click(object sender, System.EventArgs e)
{
string cpuInfo = "";//cpu序列号
ManagementClass cimobject = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
Response.Write(cpuInfo);
}
}
#endregion #region 13.主板的系列号
private void Button13_Click(object sender, System.EventArgs e)
{
ManagementObjectSearcher searcher=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
foreach(ManagementObject share in searcher.Get())
{
Response.Write("主板制造商:" + share["Manufacturer"].ToString()) ;
Response.Write("型号:" +share["Product"].ToString()) ;
Response.Write("序列号:"+share["SerialNumber"].ToString()) ;
}
}
#endregion #region 14.获取硬盘ID
private void Button14_Click(object sender, System.EventArgs e)
{
String HDid;
ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
HDid = (string)mo.Properties["Model"].Value;
Response.Write(HDid);
}
}
#endregion #region 15.获取本机的用户列表
private void Button15_Click(object sender, System.EventArgs e)
{
SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject os in searcher.Get())
{
Response.Write(os["Name"]);
}
}
#endregion
}

WMI使用集锦的更多相关文章

  1. Windows命令行命令集锦

    原文:Windows命令行命令集锦 转自:http://www.me2wg.com/bbs/forum.php?mod=viewthread&tid=15830 winver--------- ...

  2. windows 开始→运行→命令集锦

    windows 开始→运行→命令集锦 来源于网络,侵权请通知我删除 命令 说明 vwinver 检查Windows版本 wmimgmt.msc 打开windows管理体系结构(WMI) wupdmgr ...

  3. 看完SQL Server 2014 Q/A答疑集锦:想不升级都难!

    看完SQL Server 2014 Q/A答疑集锦:想不升级都难! 转载自:http://mp.weixin.qq.com/s/5rZCgnMKmJqeC7hbe4CZ_g 本期嘉宾为微软技术中心技术 ...

  4. Android之常见问题集锦Ⅱ

    Android问题集锦Ⅰ:http://www.cnblogs.com/AndroidJotting/p/4608025.html EditText输入内容改变事件监听 _edit.addTextCh ...

  5. Visual Studio问题集锦:coloader80.dll未正确安装

    问题 今天在修改之前的一个项目的时候报了一个错,大概内容如下: 有一个 Visual Studio 的 DLL 文件(coloader80.dll)未正确安装.请通过"控制面板"中 ...

  6. Eclipse for Java EE软件操作集锦(二)

    看本文章之前请确保已经了解eclipse建立web工程,如果有疑问请查看本系列文章第一篇 eclipse软件操作集锦(一) 1.我们添加一个servlet 配置一下web.xml测试一下是否能正常显示 ...

  7. Mysql 常用 SQL 语句集锦

    Mysql 常用 SQL 语句集锦 基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day fr ...

  8. C/C++面试题集锦(一)

    C/C++面试题集锦(一) */--> C/C++面试题集锦(一) 在类的头文件中进行声明然后在定义文件中实现有什么意义? 一方面使类的实现只编译一次,提高编译效率:另一方面可以实现类的接口和实 ...

  9. 通用js函数集锦<来源于网络> 【二】

    通用js函数集锦<来源于网络> [二] 1.数组方法集2.cookie方法集3.url方法集4.正则表达式方法集5.字符串方法集6.加密方法集7.日期方法集8.浏览器检测方法集9.json ...

随机推荐

  1. oralce 仅配置精简客户端 连接plsql ( 版本需一直,要不都是32要不是都是64)

    1.Oracle服务器已经安装完成,版本10.2.0. 2.访问www.oracle.com,下载Oracle精简客户端. 下载页面地址:http://www.oracle.com/technetwo ...

  2. Linux Kernel 'MSR' Driver Local Privilege Escalation

    本站提供程序(方法)可能带有攻击性,仅供安全研究与教学之用,风险自负! // PoC exploit for /dev/cpu/*/msr, 32bit userland on a 64bit hos ...

  3. Luogu 考前模拟Round. 1

    A.情书 题目:http://www.luogu.org/problem/show?pid=2264 赛中:sb题,直接暴力匹配就行了,注意一下读入和最后一句话的分句 赛后:卧槽 怎么只有40 B.小 ...

  4. 教您怎么从spring 官网下载参考文档

    假如您使用spring,那么本经验可能帮助到您. 假如您使用spring的过程中,需要查询一些文档,那么本经验可能帮助到您. 假如您对下载spring的文档有疑惑,那么本经验可能帮助到您. 教您怎么从 ...

  5. 实战weblogic集群之创建节点和集群

    一.启动weblogic,访问控制台 weblogic的domain创建完成后,接下来就可以启动它,步骤如下: $ cd /app/sinova/domains/base_domain/bin $ . ...

  6. HDOJ(HDU) 2107 Founding of HDU(找最大值)

    Problem Description 经过慎重的考虑,XHD,8600, LL,Linle以及RPG等ACM队员集体退役,甚至正在酝酿退学. 为什么?要考研?那也不用退学呀- 当然不是!真正的原因是 ...

  7. #345 div2 D. Image Preview

    Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed ...

  8. 【最短路】埃雷萨拉斯寻宝(eldrethalas) 解题报告

    问题来源 BYVoid魔兽世界模拟赛 [问题描述] 一万两千年前,当精灵还是在艾萨拉女王的统治下的时候,辛德拉就是是女王手下一名很有地位的法师了.他受任建造了一座城市,来保存女王的法师们进行魔法研究的 ...

  9. MP3播放器的实现

    今天,基本上实现了MP3播放器的基本功能,现在总结一下. 首先,下载服务器端的MP3列表,这里用到了下载技术和解析XML文件技术. 下载参考(http://blog.csdn.net/huim_lin ...

  10. jMeter接口测试案例