Several WMI examples (primary)

xiaoxiao2021-03-06  73

WMI - Windows Management Instrument, is an object-oriented database based on Web based Enterprise Management (WBEM), a standard interface that manages corporate environment development. You can use it to access some of the information and services of the local host, monitor your computer, manage remote computers ...

Add a reference in vs.net: System.Management.dll, so your project can use WMI.

WMI is flexible, but Class is also more, such as: CPU's series number -Win32_processor, motherboard BIOS series number -Win32_bios, local disk -Win32_LogicalDisk, shared resources --Win32_share, etc., detailed WMI class name can be queried in MSDN MSDN -help: //ms.vscc.2003/ms.msdnqtr.2003feb.2052/wmisdk/wmi/win32_classes.htm

You can also use WMI Tools to manage WMI service namespace namespace http://www.microsoft.com/downloads/details.aspx?familyid=6430f853-1120-48db-8cc5-f2abdc3ed314&displaylang=en

Use this program to get WMI Class Name:

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

DIM WMI As Management.ManagementClass

DIM INFO As Management.ManagementObject

'Return to WMI Class Name to String Array

Private function findwmi (byval indexstring as string, byval deep as boolean) AS String ()

Try

DIM _WMILIST () AS STRING

WMI = New Management.ManagementClass, 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.ientm ("__ class")))

Else

IF info.item ("__ class"). Tostring.Substring (0, _

IIF (Info.item ("__Class"). Tostring.Length> Chclass.length, _

Chclass.length, info.ientm ("__ class"). TOString.Length)). TOLOWER = chclass then

_Wmilist (ubound (_wmilist) = (Info.ientm ("__ class")) endiff

END IF

Application.doevents ()

NEXT

Options = Nothing

INFO = Nothing

WMI = Nothing

Return_wmilist

Catch exception

MsgBox (ex.Message, 16 0, ex. Targetsite.name)

END TRY

END FUNCTION

'Get the WMI Class INFO and write it to the output window

Private sub getinfo (byval indexstring as string)

Try

IF indexstring is nothing thrings

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

'Write WMI Class INFO to the output window

Console.writeline (Info.getText (Management.TextFormat.mof) .tostring)

NEXT

INFO = Nothing

WMI = Nothing

Catch exception

MsgBox (ex.Message, 16 0, ex. Targetsite.name)

END TRY

End Sub

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

when using it:

DIM TMPSTR () AS STRING, I AS INTEGER

'Get the Class Name of WMI

TMPSTR = FindWMI (Nothing, True)

'List 559 of Class 559 in Class Name Array Info

GetInfo (Tmpstr (559))

'Lists information about physical memory

GetInfo ("Win32_PhysicalMemory")

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

Some examples were collected below;

Get information about local hard drives:

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

Drive Type Disk ("DriveType"):

Value = 2

Value = 3

Value = 4

Value = 5

Value = 6floppy disk

Hard Disk

Network drive

CDROM

Ram Disk

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

From the newly launched remote computer: (requires permissions)

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM CO As ConnectionOptions = New ConnectionOptions

Co. HUSERNAME = "admin" 'Login User Name

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 * WIN32_OPERATISTEM")

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.to.tostring ())

NEXT

End Sub

End module

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

Create a process:

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, NOTING)

Console.Writeline ("Creation of Calculator Process Returned:" Outparams ("ReturnValue"))

Console.writeline ("Process ID:" & Outparams ("Processid")))))

End Subend Module

End a process:

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM service as managementObject = new management ("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 ("Status:" & Outparams ("ReturnValue"))

End Sub

End module

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

Get the directory of the remote machine and the file information:

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

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

Get physical memory size:

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM strComputer = "computername" 'computer name

DIM WBEMSERVICES, WBEMOBJECTSET, WBEMOBJECT

WbemServices = getObject ("WinMgmts: //" & struct

WBemObjectSet = WbemServices.instanceSof ("Win32_LogicalMemoryConfiguration")

For Each WBemObject in WbemObjectset

Console.writeline ("Physical Memory Size (KB):" & WbemObject.totalphysicalMemory)

NEXT

End Sub

End module

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

Get available memory sizes:

Imports system

Imports System.ManagementModule Module1

Public SUB

Main

()

DIM STRComputer As string = ".", I, intValue as integer

Dim Colitems, Objwmiservice, Objitem

Objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

'Repeating 20 reviews

For i = 1 to 20

'Generate memory snapshot

Colitems = objwmiservice.execQuery ("SELECT * WIN32_PERFRAWDATA_PERFOS_MEMORY")

For Each Objitem in Colitems

INTVALUE = Objitem.availablembytes

Console.writeline ("Available Memory Size (MB):" & INTVALUE)

'Delay 5 seconds

Threading.thread.sleep (5000)

NEXT

NEXT

End Sub

End module

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

Get service name:

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM strComputer = "computername"

DIM WBEMSERVICES, WBEMOBJECTSET, WBEMOBJECT

WbemServices = getObject ("WinMgmts: //" & struct

WBemObjectSet = WBEMSERVICES.INSTANCESOF ("Win32_Service")

For Each WBemObject in WbemObjectset

Console.WriteLine ("Service Name:" & wbemObject.displayName)

Console.writeline ("Current Status:" & WbemObject.State)

Console.writeline ("Start Mode:" & WbemObject.Startmode)

NEXT

End Sub

End module

Read logging:

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM strComputer = "MagicDog"

DIM WBEMSERVICES, WBEMOBJECTSET, WBEMOBJECT

WbemServices = getObject ("WinMgmts: //" & struct

WbemObjectSet = WBEMSERVICES.INSTANCESOF ("Win32_NTLOGEVENT")

For Each WBemObject in WbemObjectset

Console.writeline ("log file:" & wbemObject.logfile) console.writeline ("Record number:" & wbemObject.recordnumber)

Console.writeline ("Type:" & wbemObject.type)

Console.writeline ("Generation Time:" & WbemObject.timeGenerated)

Console.Writeline ("Source Name:" & wbemObject.SourceName)

Console.writeline ("Event code:" & wbemObject.eventcode)

Console.writeLine ("User" & WbemObject.user)

Console.WriteLine ("Computer Name:" & wbemObject.computername)

Console.writeline ("Information:" & wbemObject.Message)

NEXT

End Sub

End module

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

Delete log files: (Please back up first)

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 * WIN32_NTEVENTLOGFILE WHERE LOGFILENAME = '" & logs & "'")

For Each Objlogfile in Objlogfiles

Objlogfile.cleareventlog ()

NEXT

NEXT

End Sub

End module

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

Use performance counters:

Imports system

Imports System.Management

Module Module1

Public SUB

Main

()

DIM STRComputer As string = ".", I, intValue as integer

Dim Colitems, Objwmiservice, Objitemobjwmiservice = GetObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

FOR i = 1 to 5

Thieading.thread.sleep (1000)

Colitems = Objwmiservice.execQuery ("SELECT * WIN32_PERFRAWDATA_PERFPROC_PROCESS WHERE Name = 'devenv'")

For Each Objitem in Colitems

INTVALUE = Objitem.Handlecount

Console.writeLine ("Opened Handle Number:" & INTVALUE)

NEXT

NEXT

End Sub

End module

Creating an object using the getObject function is used in the script, so the parameter is the tagname "Winmgmts:" and target computer name of the WMI script library, the above STRComputer = "." It is equivalent to localhost, if it is executed on the remote computer. " "Change this corresponding computer name.

among them:

ManagementObject: single management object

ManagementClass: Single Management Class

ManagementObjectSearcher: Query the collection of management objects and management classes

Managementeventwatcher: Monitoring events from WMI

ManagementQuery: Used as the basis for all query classes.

You can also create from the script:

SET OLOCATOR = CreateObject ("wbemscripting.swbemlocator") 'new swbemlocatorif err.Number <> 0 THEN MSGBOX "Windows Management (WMI) cannot be created" & 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 'From New NEXT

WMI's overview Please refer to MSDN or http://www.9cbs.net/develop/Article/19/19157.shtm

转载请注明原文地址:https://www.9cbs.com/read-109236.html

New Post(0)