WMI的几种写法

时间:2021-08-19 19:22:14

WMI的一种写法:
Set oWMI = GetObject("winmgmts:" & _
                     "{impersonationLevel=impersonate,(Shutdown)}!" & _
                     "\\." & _
                     "\root\cimv2")
Set cNAs = oWMI.ExecQuery("Select * from Win32_NetworkAdapter")
For Each oNA in cNAs
  WScript.Echo oNA.MACAddress
Next
特点:像SQL语句一样,因此就可以加上where语句,如:
WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))

WMI的另一种写法:
Set cNAs = GetObject("winmgmts:" & _
                     "{impersonationLevel=impersonate,(Shutdown)}!" & _
                     "\\." & _
                     "\root\cimv2").InstancesOf("Win32_NetworkAdapter")
For Each oNA in cNAs
  WScript.Echo oNA.MACAddress
Next
特点:有命名空间下的类生成实例的感觉

如果要获取Win32_NetworkAdapter的所有属性,可以这样写
Set oNA = GetObject("winmgmts:" & _
                    "{impersonationLevel=impersonate,(Shutdown)}!" & _
                    "\\." & _
                    "\root\cimv2" & _
                    ":Win32_NetworkAdapter")
For Each oProperty in oNA.Properties_
  WScript.Echo oProperty.Name
Next
这个WMI包含了前缀:"winmgmts:";安全设置:"{......}!";计算机名字:"\\.
";CIM命名空间:"\root\cimv2";WMI类名:":WMIClassesName"。
得到的只是一个类对象,还没实例化。

安全设置中包含(ShutDown)是没有必要的,原来是测试Win32_OperatingSystem的ReBoot功能,后来怕以后不小心双击就重启,改为用Win32_NetworkAdapter来代替。但(Shutdown)却忘了册,也舍不得,因为还没理解。