WMI question answer highlights

xiaoxiao2021-03-06  75

WMI use skills set a lot of friends may have seen the WMI, but I don't know how to understand the knowledge of WMI. I can always find the right information. Some information on the Internet is not a lot of mistakes. It is not clear. When I have time, I will concentrate on WMI's knowledge and put it here for everyone to learn. This post will continue to increase. 1. What is WMIWMI is a short-term English Windows Management Instrumentation, and its function is mainly: access to some information and services to the local host, you can manage remote computers (of course you have to have enough permissions), such as restart, shutdown, close Process, create a process, etc. 2, how to use WMI to get information about local disks? First, create a project in VS.NET, then reference a .NET accessory: System.Management.dll, so your project can use WMI. The code is as follows: use system; using system.management;

class Sample_ManagementObject {public static int Main (string [] args) {SelectQuery query = new SelectQuery ( "Select * From Win32_LogicalDisk"); ManagementObjectSearcher searcher = new ManagementObjectSearcher (query); foreach (ManagementBaseObject disk in searcher.Get ()) {Console .Writeline ("/ r / n" disk ["name"] " "] " " "" "" "" "" "" "" "" ""]);

Console.readline ();

Return 0;

}

}

The return value of Disk [DriveType "] is as follows:

1 NO Type 2 Floppy Disk 3 Hard Disk 4 Removable Drive or Network Drive 5 CD-ROM 6 RAM DISK

3, how to get the capacity of the specified disk with WMI? Using system.management;

// This example demonstrates reading a property of a ManagementObject.class Sample_ManagementObject {public static int Main (string [] args) {ManagementObject disk = new ManagementObject ( "win32_logicaldisk.deviceid = /" c: / ""); disk.Get ( ); Console.writeline ("Logical Disk size =" disk ["size"] "bytes"); console.readline (); return 0;}}

4. How do I list all the shared resources in the machine? Using system.management;

class TestApp {[STAThread] static void Main () {ManagementObjectSearcher searcher = new ManagementObjectSearcher ( "SELECT * FROM Win32_share"); foreach (ManagementObject share in searcher.Get ()) {Console.WriteLine (share.GetText (TextFormat.Mof) );}}} Don't forget to add System.Management to the reference.

5. How do you write a folder in your system to share or cancel your sharing.? First, this needs to log in to the system with the corresponding permissions. Then, try the following code: use system; use system.management;

Class Createshare {public static void main (string [] args) {managementclass _class = new managementPath (New ManagementPath);

Object [] obj = {"c: // Temp", "My Sharing", 0, 10, "DOT NET implementation", "}"

_Class.InvokeMethod ("create", obj);}} will use Object [] Obj = {"C: // Temp", "My Sharing", 0, 10, "DOT NET implementation", "}" Change to Object [] Obj = {"C: // Temp", "My Sharing", 0, Null, "DOT NET implementation sharing", "};"} can be implemented to maximum user.

6, how to get the operating status of the system service? private void getServices () {ManagementObjectCollection queryCollection; string [] lvData = new string [4]; try {queryCollection = getServiceCollection ( "SELECT * FROM Win32_Service"); foreach (ManagementObject mo in queryCollection) {// create child node for operating system LVDATA [0] = Mo ["name"]. Tostring (); lvdata [1] = mo ["startmode"]. toString (); if (Mo ["Started"]. Equals (true)) LVData [2] = "Start"; else lvdata [2] = "stop"; lvdata [3] = mo ["startname"]. Tostring (); // create list item listviewItem lvitem = new listviewItem (lvdata, 0); listviewservices.Items .Add (lvitem);}} catch (exception e) {messagebox.show ("Error:" E);}}

7. Modify IP via WMI, do not restart? using System; using System.Management; using System.Threading; namespace WmiIpChanger {class IpChanger {[MTAThread] static void Main (string [] args) {ReportIP (); // SwitchToDHCP (); SwitchToStatic (); Thread.Sleep ( 5000); reportip (); console.writeline ("end.");}

static 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;}}

static void SwitchToStatic () {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 ("iPadDress"); INPAR ["ipaddress"] = new string [] {"192.168.1.1"}; inPar ["SubnetMask"] = new string [] {"255.255.255.0"}; outpar = Mo.invokeMethod ("enablestatic", inPar, null; Break;}}

static void ReportIP () {Console.WriteLine ( "****** Current IP addresses:"); ManagementClass mc = new ManagementClass ( "Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances (); foreach (ManagementObject mo in moc ) {IF ("iPenabled"]) Continue; console.writeline ("{0} / n svc: '{1}' Mac: [{2}]", (String) Mo ["CAPTION "], (String) Mo [" serviceename "], (String) Mo [" Macaddress "]);

String [] addresses = (String []) Mo ["ipaddress"]; string [] subnets = (String []) Mo ["IPSUBNET"];

Console.writeline ("Addresses:") Console.WriteLine ("/ T '{0}'", SAD);

Console.writeline ("Subnets:"); Foreach (String Sub in subnets) console.writeline ("/ t '{0}'", SUB);}}}}

8. How do I use WMI to remotely restart remote computers? Using system; usingspace wmi3 {///

/// summary description for class1. /// class class1 {static void main (string [] args) {console.writeline Computer details retrieved using Windows Management Instrumentation (WMI) "); Console.WriteLine (" mailto: Written 02/01/02 By John O'Donnell - csharpconsulting@hotmail.com "); Console.WriteLine ("================================================================================================================================================================= ========================== "); / / Connect the remote computer ConnectionOptions co = new connectionOptions (); Co. HUSERNAME =" john "; CO .Password = "john"; System.Management.ManagementScope ms = new System.Management.ManagementScope ( "192.168.1.2//root//cimv2", co); // query the remote computer 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); console.writeline (mo.to.toTRING ());}}}} 9, use WMI to create a new process? Using system.management;

// this Sample Demonstrates Invoking A WMI Method Using Parameter Objectspublic Class InvokeMethod {public static void main () {

// Get the object on which the method will be invoked managementclass processclass = new managementclass ("win32_process");

// Get An Input Parameters Object for this method management = processclass.getMethodParameters ("create");

// Fill in Input Parameter Values ​​INPARES ["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 Console.WriteLine ( "Creation of calculator process returned:" outParams [ "returnvalue"]); Console.WriteLine ("Process ID:" Outparams ["Processid"]);}}

10. How to terminate a process via WMI? Using system.management;

// This example demonstrates how to stop a system service class Sample_InvokeMethodOptions {public static int Main (string [] args) {ManagementObject service = new ManagementObject ( "win32_service = /" winmgmt / "");. InvokeMethodOptions options = new InvokeMethodOptions () Options.timeout = New Timespan (0, 0, 0, 5);

ManagementBaseObject Outparams = Service.InvokeMethod ("StopService", NULL, OPTIONS

Console.writeline ("Return Status =" Outparams ["ReturnValue"]); Return 0;}}

11. How to use WMI to get the directory of the remote machine and files. For example, how to list all files in a directory, or all subdirectories; how to delete, add, change files? USING SYSTEM;

Using system.management;

// This Example Demonstrates Reading a property of a managementObject.

Class Sample_ManagementObject

{

Public static int main (string [] args) {

ManagementObject Disk = new managementObject

"Win32_LogicalDisk.DeviceId = /" c: / "");

Disk.get ();

Console.writeline ("Logical Disk size =" Disk ["Size"] "Bytes");

Return 0;

}

}

12. References can be refer to the following:

MSDN WMI SDK: http://msdn.microsoft.com/library/default.asp? URL = / library / en- us / wmisdk / wmi / wmi_start_page.asp

WMI User Instructions (9CBS): http://www.9cbs.net/develop/Article/15/15346.shtm

WMI technology application for .NET (9CBS): http://www.9cbs.net/develop/Article/16/16419.shtm

Easily gain system information (1) -wmi article (9cbs) in .NET: http://www.9cbs.net/develop/Article/15/15744.shtm

:)

13, some tips I use WMI to take out the NIC's MAC address, the CPU's series number, the motherboard's series number, where the motherboard's series number has been checked, and the rest have to be verified, because I am using a notebook, notebook There is a series number of a motherboard on the back, so it is sure that the motherboard series number is no problem.

MAC address of the NIC

Select Macaddress from Win32_NetworkAdapter Where (Macaddress is not null) and (Manufacturer <> Microsoft ')))

RESULTS: 08: 00: 46: 63: FF: 8C

CPU's series number

SELECT Processorid from Win32_Processor

Result: 3FEBF9FF00000F24

Motherboard series number

SELECT SerialNumber from Win32_BIOS

Results: 28362630-3700521 obtaining hard IDString HDid; ManagementClass cimobject = new ManagementClass ( "Win32_DiskDrive"); ManagementObjectCollection moc = cimobject.GetInstances (); foreach (ManagementObject mo in moc) {HDid = (string) mo.Properties [ "Model" ] .value;

MessageBox.Show (HDid);} 14, an exception handling problems after finishing I WMI following is a section of code ManagementObjectCollection queryCollection1;. ConnectionOptions co = new ConnectionOptions (); co.Username = "administrator"; co.Password = "111"; try {System.Management.ManagementScope ms = new System.Management.ManagementScope (@ "// csnt3 / root / cimv2", co); System.Management.ObjectQuery oq = new System.Management.ObjectQuery ( "SELECT * From win32_operatingsystem "); ManagementObjectSearcher Query1 = New ManagementObjectSearcher (MS, OQ);

QueryCollection1 = query1.get (); foreach (management) {string [] ss = {"}; mo.invokeMethod (" reboot ", ss); console.writeline (mo.to.tostring ());}} Catch (Exception EE) {

Console.writeline ("Error");

}

15. Windows Management Specification (WMI) is a scalable system management structure that uses a unified, standard, scalable-oriented interface. WMI provides you with standard methods for interacting with system management information and basic WMI API. WMI is mainly used by system management application developers and administrators to access and operating system management information. WMI can be used to generate tools for organization and management system information, enabling administrators or system managers to monitor system activities more closely. For example, you can use WMI to develop an application that calls administrators when the web server crashes. The WMI provides a large number of specifications with the .NET framework for WMI to achieve almost any management tasks for many high-end applications (eg, Microsoft Exchange, Microsoft SQL Server, and Microsoft Internet Information Services (IIS)). The administrator can perform the following tasks: • Monitor the health of the application. • Detect bottlenecks or malfunctions. ? Manage and configure applications. ? Query application data (traversal and query using object relationship). • Perform a seamless local or remote management operation. The WMI structure consists of the following three layers: • The client uses the WMI execution operation (for example, reading the software components of the management details, configuring the system, and subscription events). Object Manager Provide Intermediate Devices and Clients, which provides some key services, such as standard event publishing and subscription, event filtering, query engine, etc. • Provider software components that capture real-time data and return it to the client application to process methods from the client call and link the client link to the underlying structure of the managed. Data and events are seamlessly provided to the client and applications through a well-defined architecture. In the .NET framework, System.Management namespaces provide public classes used to traverse WMI architectures. In addition to the .NET framework, you need to install WMI on your computer to use the management functions in this namespace. If you are using Windows Millennium Edition, Windows 2000 or Windows XP, WMI has been installed. Otherwise, WMI will be downloaded from MSDN. Use the System.Management Access Management Information System.Management Namespace Yes WMI Namespace in the .NET Framework. This namespace includes the following first-level class objects that support WMI operations: • ManagementObject or ManagementClass: Single management object or class, respectively. "ManagementObjectSearcher: Used to retrieve the collection of ManagementObject or Management Class objects based on the specified query or enumerate. ManagementEventWatcher: It is used to book event notifications from WMI. ? ManagementQuery: Used as the foundation of all query classes. The use coding example of the System.Management class is very suitable for the .NET framework environment, and WMI uses a standard base framework when any appropriate time. For example, WMI is widely utilized. NET set class and uses recommended encoding modes, such as "delegate" modes for .NET asynchronous. Therefore, developers using the .NET framework can use their current skills to access management information about the computer or application.

See Using WMI Management Applications | Retrieval Management Objects | Query Management Information | Booking and Using Administrative Event | Method for Performing Management Objects | Remote Processing and Connection Options | Using Strong Type Object Get CPU Serial Number Code String CPUInfo = " ; // cpu SEQ ID ManagementClass cimobject = new ManagementClass ( "Win32_Processor"); ManagementObjectCollection moc = cimobject.GetInstances ();. foreach (ManagementObject mo in moc) {cpuInfo = mo.Properties [ "ProcessorId"] value.ToString () ; Console.WriteLine (cpuInfo); Console.ReadLine ();} NIC hardware address acquisition using System.Management; ... ManagementClass mc = new ManagementClass ( "Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances (); foreach (ManagementObject Mo in moc) {IF ((Bool) Mo ["iPenabled"] == True) Console.writeline ("Mac Address / T {0}", Mo ["Macaddress"]. TOSTRING ()); Mo.dispose );}} acquired hard IDString HDid; ManagementClass cimobject = new ManagementClass ( "Win32_DiskDrive"); ManagementObjectCollection moc = cimobject.GetInstances (); foreach (ManagementObject mo in moc) {HDid = (string) mo.Properties [ "Model"] .value; messagebox.show (hdid);} 16, easily obtain system information in .NET (1) -WMI article MONTAQUE Declimination: 1, personal personal experience, for reference 2, when reprint, please keep it.

Overview: Don't know if you have this experience? Sometimes in order to obtain a little bit of information, such as considering the version number of the operating system, or the resolution of the current screen. In fact, the end is a property value for reading an operating system, and then seeing our programs in the dense Win32 API declaration, call, code readability and maintenance. When it comes to .NET, Microsoft provides a more rich class, and there are many ways to call the API before. Net easily and easy to implement. Today, it is briefly introduced to how to obtain information from the WMI (Windows Management Specification) in .NET. Main ideas: Establish an example of obtaining an operating system sharing directory and obtaining a motherboard number, showing how to use the class get the system under System.Managment:

Text: WMI (Windows Management Specification: Windows Management Instrument) is an implementation of Microsoft's Web-based Enterprise Management (WBEM) and is also a standard-based system management interface. WMI earliest appears on the Microsoft Windows 2000 system, but it can also be installed on Windows NT 4 and Windows 9x computers. WMI is a powerful tool for easy access to system information. In .NET, there is a system.management name space (the system is not referenced by default, we can manually add a reference), by the following Class's operation, you can query the information of the system software and hardware, first look at a simple example: imports system. ManagementDim searcher As New ManagementObjectSearcher ( "SELECT * FROM Win32_share") Dim share As ManagementObject For Each share in searcher.Get () MessageBox.Show (share.GetText (TextFormat.Mof)) Next share the results of running the system lists all Current shared directory, and description, etc.

Analyze the above code, you can see some points: 1. It seems to be in the database operation, a bit like a SQL statement. In fact, it is SQL operation, this statement is formed into WQL (WMI Query Language), in fact, a subset of standard SQL plus WMI extensions. 2, WQL is a read-only query language, we can only query the response data Can not use Update, INSERT and other update operations 3, the code is simple, easy to understand 4, we use a MOF (managed object format) display.

Example 2: Getting the information on the current motherboard is a software information, look at an example of obtaining hardware information, get the serial number of the motherboard and the manufacturer: DIM Searcher AS New ManagementObjectSearcher ("SELECT * FROM WIN32_BASEBOARD") DIM Share As ManagementObject for Each Share in Searcher.get () Debug.writeline ("MAUFACTURER:") Debug.Writeline ("Model:" & Share ("Product")) Debug.writeline "Serial number:" & Share ("serialnumber")) Next Share summary and supplementation: WMI class is also a hierarchy, and you can refer to WMI in MSDN; when you turn to .NET platform development, it is best to look at some about. This paper introduces NET, which can greatly enhance the development efficiency and operational efficiency of code.

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

New Post(0)