CSDN博客

img benlee

几个 WMI 的例子(初级)

发表于2004/10/9 8:46:00  655人阅读

WMI - Windows Management Instrumentation,是基于 Web Based Enterprise ManagementWBEM)的面向对象数据库,一个管理企业环境开发的标准接口。可以利用它访问本地主机的一些信息和服务、监视计算机、管理远程计算机

VS.NET中需要添加引用:System.Management.dll,这样你的项目才能使用WMI

WMI 的使用灵活,但 class 也多,如:CPU的系列号-Win32_Processor、主板BIOS的系列号-Win32_BIOS、本地磁盘-Win32_LogicalDisk共享资源-Win32_share等等,详细的 WMI 类名可以在MSDN中查询 ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/wmisdk/wmi/win32_classes.htm

也可以使用WMI Tools管理WMI服务的名称空间http://www.microsoft.com/downloads/details.aspx?FamilyId=6430F853-1120-48DB-8CC5-F2ABDC3ED314&displaylang=en

用这个程序也可以获取WMI Class Name

 

---------------------------------------------------------------------------------------

    Dim WMI As Management.ManagementClass

    Dim info As Management.ManagementObject

返回 WMI 的 Class Name 到 String Array

    Private Function FindWMI(ByVal IndexString As String, ByVal Deep As Boolean) As String()

        Try

            Dim _WMIList() As String

            WMI = New Management.ManagementClass

            Dim options As New Management.EnumerationOptions

            Dim chClass As String = Nothing

            If Not IndexString Is Nothing Then

                chClass = IndexString

            End If

            options.EnumerateDeep = Deep

            For Each info In WMI.GetSubclasses(options)

                If _WMIList Is Nothing Then

                    ReDim _WMIList(0)

                Else

                    ReDim Preserve _WMIList(UBound(_WMIList) + 1)

                End If

                If chClass Is Nothing Then

                    _WMIList(UBound(_WMIList)) = (info.Item("__Class"))

                Else

                    If info.Item("__Class").ToString.Substring(0, _

                       IIf(info.Item("__Class").ToString.Length > chClass.Length, _

                       chClass.Length, info.Item("__Class").ToString.Length)).ToLower = chClass Then

                        _WMIList(UBound(_WMIList)) = (info.Item("__Class"))

                    End If

                End If

                Application.DoEvents()

            Next

            options = Nothing

            info = Nothing

            WMI = Nothing

            Return _WMIList

        Catch ex As Exception

            MsgBox(ex.Message, 16 + 0, ex.TargetSite.Name)

        End Try

    End Function

获取 WMI 的 Class Info 并将其写入输出窗口

    Private Sub GetInfo(ByVal IndexString As String)

        Try

            If IndexString Is Nothing Then Exit Sub

            Dim wmiClass As String = IndexString

            WMI = New Management.ManagementClass(wmiClass)

            Dim strInfo As String

            Console.WriteLine("WMI Class is:" & wmiClass)

            For Each info In WMI.GetInstances

WMI Class Info 写到输出窗口

                Console.WriteLine(info.GetText(Management.TextFormat.Mof).ToString)

            Next

            info = Nothing

            WMI = Nothing

        Catch ex As Exception

            MsgBox(ex.Message, 16 + 0, ex.TargetSite.Name)

        End Try

    End Sub

---------------------------------------------------------------------------------------

使用时:

            Dim tmpStr() As String, i As Integer

            '获取 WMI 的 Class Name

            tmpStr = FindWMI(Nothing, True)

            '列出 Class Name Array 中的第 559 个 Class 的 Info

            GetInfo(tmpStr(559))

            '列出物理内存的信息

            GetInfo("Win32_PhysicalMemory")


---------------------------------------------------------------------------------------

下面收集了一些例子;

获取本地硬盘的信息:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim disk As ManagementObject = New ManagementObject("win32_logicaldisk.deviceid=""c:""")

        disk.Get()

        Console.WriteLine("Logical disk size is " + disk("Size").ToString + " bytes")

    End Sub

End Module

 

驱动器类型disk(“DriveType”)

Value=2

Value=3

Value=4

Value=5

Value=6

Floppy disk

Hard disk

network drive

CDROM

RAM Disk

 

---------------------------------------------------------------------------------------

从新启动远程计算机:(需要权限)

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim co As ConnectionOptions = New ConnectionOptions

        co.Username = "Admin"'登录的用户名称

        co.Password = "12345678"'Password

        Dim ms As System.Management.ManagementScope = New System.Management.ManagementScope("//192.168.1.2/root/cimv2", co)

        Dim oq As System.Management.ObjectQuery = New System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem")

        Dim mos As ManagementObjectSearcher = New ManagementObjectSearcher(ms, oq)

        Dim _query As ManagementObjectCollection = mos.Get()

        Dim mo As ManagementObject

        For Each mo In _query

            Dim tmp() As String = {""}

            mo.InvokeMethod("Reboot", tmp)

            Console.WriteLine(mo.ToString())

        Next

    End Sub

End Module

 

---------------------------------------------------------------------------------------

建立一个进程:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim processClass As ManagementClass = New ManagementClass("Win32_Process")

        Dim inParams As ManagementBaseObject = processClass.GetMethodParameters("Create")

        inParams("CommandLine") = "calc.exe"

        Dim outParams As ManagementBaseObject = processClass.InvokeMethod("Create", inParams, Nothing)

        Console.WriteLine("Creation of calculator process returned: " + outParams("returnvalue"))

        Console.WriteLine("进程 ID:" & outParams("processId"))

    End Sub

End Module

 

结束一个进程:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim service As ManagementObject = New ManagementObject("win32_service=""winmgmt""")

        Dim options As InvokeMethodOptions = New InvokeMethodOptions

        options.Timeout = New TimeSpan(0, 0, 0, 5)

        Dim outParams As ManagementBaseObject = service.InvokeMethod("StopService", Nothing, options)

        Console.WriteLine("状态:" & outParams("Returnvalue"))

    End Sub

End Module


---------------------------------------------------------------------------------------

 

获取远程机器的目录以及文件信息:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim disk As ManagementObject = New ManagementObject("win32_logicaldisk.deviceid=""c:""")

        disk.Get()

        Console.WriteLine("硬盘容量大小(bytes): " & disk("Size"))

    End Sub

End Module

 

---------------------------------------------------------------------------------------

获取物理内存大小:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer = "ComputerName" '计算机名

        Dim wbemServices, wbemObjectSet, wbemObject

        wbemServices = GetObject("winmgmts://" & strComputer)

        wbemObjectSet = wbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

        For Each wbemObject In wbemObjectSet

            Console.WriteLine("物理内存的大小 (kb):" & wbemObject.TotalPhysicalMemory)

        Next

    End Sub

End Module

 

---------------------------------------------------------------------------------------

获取可用内存大小:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer As String = ".", i, intValue As Integer

        Dim colItems, objWMIService, objItem

 

        objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")

'重复执行 20 次检查

        For i = 1 To 20

'产生内存快照

            colItems = objWMIService.ExecQuery("Select * From Win32_PerfRawData_PerfOS_Memory")

            For Each objItem In colItems

                intValue = objItem.AvailableMbytes

                Console.WriteLine("可用内存大小 (MB): " & intValue )

'延时 5 秒

                Threading.Thread.Sleep(5000)

            Next

        Next

    End Sub

End Module

 

---------------------------------------------------------------------------------------

获取服务名:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer = " ComputerName"

        Dim wbemServices, wbemObjectSet, wbemObject

        wbemServices = GetObject("winmgmts://" & strComputer)

        wbemObjectSet = wbemServices.InstancesOf("Win32_Service")

        For Each wbemObject In wbemObjectSet

            Console.WriteLine("服务名称:" & wbemObject.DisplayName)

            Console.WriteLine("当前状态:" & wbemObject.State)

            Console.WriteLine("启动模式:" & wbemObject.StartMode)

        Next

    End Sub

End Module


 

读取日志记录:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer = "magicdog"

        Dim wbemServices, wbemObjectSet, wbemObject

        wbemServices = GetObject("winmgmts://" & strComputer)

        wbemObjectSet = wbemServices.InstancesOf("Win32_NTLogEvent")

        For Each wbemObject In wbemObjectSet

            Console.WriteLine("日志文件:" & wbemObject.LogFile)

            Console.WriteLine("记录号:" & wbemObject.RecordNumber)

            Console.WriteLine("类型:" & wbemObject.Type)

            Console.WriteLine("产生时间:" & wbemObject.TimeGenerated)

            Console.WriteLine("源名称:" & wbemObject.SourceName)

            Console.WriteLine("事件代码:" & wbemObject.EventCode)

            Console.WriteLine("用户" & wbemObject.User)

            Console.WriteLine("计算机名:" & wbemObject.ComputerName)

            Console.WriteLine("信息:" & wbemObject.Message)

        Next

    End Sub

End Module

 

---------------------------------------------------------------------------------------

删除日志文件:(请先备份)

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer = "."

        Dim objWMIService, objLogFiles, objLogFile, logs, mylogs(3)

        objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Backup)}!//" & strComputer & "/root/cimv2")

        mylogs(1) = "application"

        mylogs(2) = "system"

        mylogs(3) = "security"

        For Each logs In mylogs

            objLogFiles = objWMIService.ExecQuery("Select * from Win32_NTEventLogFile where LogFileName='" & logs & "'")

            For Each objLogFile In objLogFiles

                objLogFile.ClearEventLog()

            Next

        Next

    End Sub

End Module

 

---------------------------------------------------------------------------------------

使用性能计数器:

Imports System

Imports System.Management

 

Module Module1

    Public Sub Main()

        Dim strComputer As String = ".", i, intValue As Integer

        Dim colItems, objWMIService, objItem

        objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")

        For i = 1 To 5

            Threading.Thread.Sleep(1000)

            colItems = objWMIService.ExecQuery("Select * From Win32_PerfRawData_PerfProc_Process Where Name = 'devenv'")

            For Each objItem In colItems

                intValue = objItem.HandleCount

                Console.WriteLine("打开的句柄数 :" & intValue)

            Next

        Next

    End Sub

End Module

 

使用Getobject函数创建对象多用于脚本中,所以参数为WMI脚本库的标记名"winmgmts:"和目标电脑名,上述的strComputer="."相当于localhost,若在远程计算机上执行则需将”.”改这相应的计算机名。

 

其中:

ManagementObject:单个管理对象

ManagementClass:单个管理类

ManagementObjectSearcher:查询管理对象及管理的集合

ManagementEventWatcher:监视来自 WMI 的事件

ManagementQuery:用作所有查询类的基础。

 

也可以从脚本中创建:

Set oLocator = CreateObject("WbemScripting.SWbemLocator") ' New SWbemLocator
If Err.Number <> 0 Then
    MsgBox "Windows Management (WMI)
不能被创建” & Err.Description
    WScript.Quit(0)
End If

-----------------------------------------------------------------------

set locator = createobject("WbemScripting.SwbemLocator")
set server = locator.ConnectServer ("//192.168.0.1/root/cimv2","username","password")
set p_obj = server.execquery("select * form Win32_operatingsystem")
for each p_objswbem in p_obj
   p_objswbem.reboot ‘
从新启动

next

 

  WMI 的有关概述请参考 MSDN http://www.csdn.net/develop/Article/19/19157.shtm

阅读全文
0 0

相关文章推荐

img
取 消
img