WMI answer highlights

Source: Internet
Author: User
Tags dot net

WMI tips
Many of my friends may have met WMI but do not have a deep understanding of it. I am also very interested in WMI knowledge. I have been searching for inappropriate information. Some information on the Internet is not wrong, I can't explain it clearly. When I have time, I will concentrate on WMI knowledge and put it here for your convenience. This post will be continuously added.
1. What is WMI?
WMI is short for Windows Management Instrumentation. Its function is mainly to access some information and services on the local host and manage remote computers (of course, you must have sufficient permissions ), for example, restart, shut down, shut down the process, and create a process.
2. How can I use WMI to obtain information about a local disk?
First, you must create a project in vs. net, and then reference A. net installation accessory: system. Management. dll in the Add reference, so that your project can use WMI.CodeAs follows:
Using 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"] + "" + disk ["drivetype"] + "" + disk ["volumename"]);
}

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
CD-ROM
6 RAM disk

3. How can I use WMI to obtain the capacity of a specified disk?
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 ");
Console. Readline ();
Return 0;
}
}

4. How to list all the shared resources on the machine?
Using system;
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 ));
}
}

}
Do not forget to add system. Management in the reference.

5. How can I write a process control to share a folder in the system or cancel sharing .?
First, you must log on to the system as a user with the relevant permissions. Then, try the following code:
Using system;
Using system. Management;

Class createshare
{
Public static void main (string [] ARGs)
{
Managementclass _ class = new managementclass (New managementpath ("win32_share "));

Object [] OBJ = {"C: \ Temp", "my shares", "share implemented by dot net ",""};

_ Class. invokemethod ("CREATE", OBJ );
}
}
Set
Object [] OBJ = {"C: \ Temp", "my shares", "share implemented by dot net ",""};
Change
Object [] OBJ = {"C: \ Temp", "my shares", 0, null, "share implemented by dot net ",""};
You can grant permissions to the most users.

6. How to obtain the running status of system services?
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] = "started ";
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. How can I modify the IP address Through WMI without restarting?
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 ()
{< br> managementbaseobject inpar = NULL;
managementbaseobject outpar = NULL;
managementclass MC = new managementclass ("win32_networkadapterconfiguration");
managementobjectcollection MOC = MC. getinstances ();
foreach (managementobject Mo in MoC)
{< br> If (! (Bool) Mo ["ipenabled"])
continue;

inpar = Mo. getmethodparameters ("enablestatic");
inpar ["IPaddress"] = new string [] {"192.168.1.1 "};
inpar ["subnetmask"] = new string [] {"255.255.255.0"};
outpar = Mo. invokemethod ("enablestatic", inpar, null);
break;
}< BR >}

Static void reportip ()
{
Console. writeline ("****** current IP addresses :");
Managementclass MC = new managementclass ("win32_networkadapterconfiguration ");
Managementobjectcollection MOC = mc. getinstances ();
Foreach (managementobject Mo in MoC)
{
If (! (Bool) Mo ["ipenabled"])
Continue;

Console. writeline ("{0} \ n svc: '{1}' Mac: [{2}]", (string) Mo ["caption"],
(String) Mo ["servicename"], (string) Mo ["macaddress"]);

String [] addresses = (string []) Mo ["IPaddress"];
String [] subnets = (string []) Mo ["ipsubnet"];

Console. writeline ("addresses :");
Foreach (string sad in addresses)
Console. writeline ("\ t' {0} '", sad );

Console. writeline ("subnets :");
Foreach (string sub in subnets)
Console. writeline ("\ t' {0} '", sub );
}
}
}
}

8. How can I remotely restart a remote computer Using WMI?
Using system;
Using system. Management;
Namespace wmi3
{
/// <Summary>
/// Summary description for class1.
/// </Summary>
Class class1
{
Static void main (string [] ARGs)
{
Console. writeline ("Computer details retrieved using Windows Management Instrumentation (Wmi )");
Console. writeline ("mailto: Written % 2002/01/02% 20by % 20 John % 20o 'Donnell % 20-% 20csharpconsulting@hotmail.com ");
Console. writeline ("========================================== ===
===================================== ");
// Connect to a remote computer
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 );
// Query remote computers
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. tostring ());
}
}
}
}

9. Use WMI to create a new process?
Using system;
Using system. Management;

// This sample demonstrates invoking a WMI method using parameter objects
Public 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
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
Console. writeline ("creation of calculator process returned:" + outparams ["returnvalue"]);
Console. writeline ("process ID:" + outparams ["processid"]);
}
}

10. How to terminate a Process Through WMI?
Using system;
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 can I use WMI to obtain directories and files of remote machines? For example, how can I list all files in a directory or all subdirectories? How can I delete, lick, and modify 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
You can refer to the following content:

Msdn wmi sdk:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/wmisdk/WMI/wmi_start_page.asp

WMI usage instructions (csdn ):
Http://www.csdn.net/develop/article/15/15346.shtm

Application of WMI Technology for. Net (csdn ):
Http://www.csdn.net/develop/article/16/16419.shtm

Easily obtain system information in. Net (1)-WMI (csdn ):
Http://www.csdn.net/develop/article/15/15744.shtm

:)

13. Tips
I can use WMI to retrieve the MAC address of the NIC, the serial number of the CPU, and the serial number of the motherboard. Among them, the serial number of the motherboard has been checked correctly, and the rest are to be verified, because I use a notebook and there is a Series Number of the motherboard on the back of the notebook, I can be sure that the series number of the motherboard is correct.

MAC address of the NIC

Select macaddress from win32_networkadapter where (macaddress is not null) and (manufacturer <> 'Microsoft '))

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

Serial number of the CPU

Select processorid from win32_processor

Result: 3febf9ff00000f24

Motherboard serial number

Select serialnumber from win32_bios

Result: 28362630-3700521
Obtain the hard disk ID
String 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 problem after WMI is used.
below is a piece of code I have compiled.

managementobjectcollection querycollection1;
connectionoptions CO = new connectionoptions ();
Co. username = "Administrator";
Co. password = "111";
try
{< br> system. management. management scope 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 (managementobject Mo in querycollection1)
{
String [] Ss = {""};
Mo. invokemethod ("reboot", SS );
Console. writeline (Mo. tostring ());
}
}
Catch (exception ee)
{

Console. writeline ("error ");

}

15. Windows Management Specification (Wmi) is a scalable system management structure. It adopts a unified, standard-based, and scalable object-oriented interface. WMI provides you with standard methods for interacting with system management information and basic WMI APIs. WMI is mainly used for system management applications.ProgramDevelopers and administrators can access and manage operating system information.
WMI can be used to generate organization and management system information tools so that administrators or system administrators can monitor system activities more closely. For example, you can use WMI to develop an application for calling the Administrator when the web server crashes.
Use WMI with the. NET Framework
WMI provides numerous specifications to implement almost any management tasks for many high-end applications (such as Microsoft Exchange, Microsoft SQL Server, and Microsoft Internet Information Service (IIS. The administrator can perform the following tasks:
? Monitor the running status of the application.
? Detects bottlenecks or faults.
? Manage and configure applications.
? Query application data (using object link traversal and query ).
? Perform seamless local or remote management operations.
The WMI structure consists of the following three layers:
? Client
Software components that Use WMI to perform operations (such as reading management details, configuring systems, and booking events.
? Object Manager
Provides an intermediate device between the program and the client. It provides some key services, such as standard event publishing and booking, event filtering, and query engines.
? Providers
Software components that capture real-time data and return it to the client application, process method calls from the client, and link the client to the managed infrastructure.
The well-defined architecture provides clients and applications with the ability to seamlessly configure data and events and the system. In the. NET Framework, the system. Management namespace provides public classes used to traverse the WMI architecture.
In addition to the. NET Framework, WMI must be installed on the computer to use the management functions in the namespace. If you are using Windows Millennium Edition, Windows 2000, or Windows XP, WMI has been installed. Otherwise, WMI needs to be downloaded from msdn.
Access Management Information with system. Management
The system. Management namespace is the WMI namespace in the. NET Framework. This namespace includes the following first-level objects that support WMI operations:
? Managementobject or managementclass: a single management object or class.
? Managementobjectsearcher: used to retrieve the set of managementobject or managementclass Objects Based on the specified query or enumeration.
? Managementeventwatcher: Used to book event notifications from WMI.
? Managementquery: Used as the basis for all query classes.
The encoding example for the system. Management class is suitable for the. NET Framework environment, and WMI uses the standard base framework whenever appropriate. For example, WMI widely utilizes. Net collection classes and uses the recommended encoding mode, such as the "delegate" mode of. Net asynchronous operations. Therefore, developers using the. NET Framework can use their current skills to access management information about computers or applications.
See
Use WMI to manage applications | retrieve a collection of management objects | query Management Information | book and use management events | method of executing management objects | remote processing and connection options | use of strong objects

Code for obtaining the CPU serial number
String cpuinfo = ""; // CPU serial number
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 ();
}
Obtain the network card hardware address
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 ();
}
}
Obtain the hard disk ID
String 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 retrieve system information in. Net (1)-WMI
Montaque

Statement:
1. My personal experience is for reference only
2. Retain the original Reprinted data.

Overview:
Do you have such experiences? Sometimes, to get a little bit of information about the system, such as considering the version number of the operating system or the resolution of the current screen. In fact, in the end, it is only a property value in a certain aspect of the read operating system. Then we can see that the Win32 API in our program declares that the code is readable and maintainability is self-evident. In. net, Microsoft provides more classes, and many methods to call APIs can be easily called in. net. Today, we will briefly introduce how to get information through communication with WMI (Windows Management specifications) in. net.
Main ideas:
Here is an example of how to obtain the shared directory of the operating system and the motherboard number, and how to use the class below system. managment to obtain system-related information:

Body:
WMI (Windows Management Specification: Windows Management Instrumentation) is an implementation of Microsoft Web-Based Enterprise Management (WBEM) and a standard-based system management interface. WMI first appeared on Microsoft Windows 2000, but it can also be installed on Windows NT 4 and Windows 9x computers. WMI is a powerful tool for getting system information easily.
In. net, there is a system. management namespace (which is not referenced by the system by default. We can manually add references). Through the following class operation, we can query system software and hardware information. Let's take a look at a simple example:

Imports system. Management
Dim 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 running result lists the directories and descriptions currently shared by all systems.

Analyze the code above to see the following points:
1. It seems that the database is being operated, a bit like an SQL statement. It is actually an SQL operation. This type of statement is converted into WQL (WMI query language), which is actually a subset of standard SQL with WMI extension.
2. WQL is a read-only query language. We can only query the response data and cannot use update, insert, or other update operations.
3. The code is simple and easy to understand.
4. We use a MOF (managed object format) display.

Example 2: obtain information about the current motherboard
the above example is a software information. The following describes an example of obtaining hardware information to obtain 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 ("motherboard manufacturer:" & share ("manufacturer")
debug. writeline ("model:" & share ("product")
debug. writeline ("serial number:" & share ("serialnumber")
next share
summary and Supplement:
the WMI class is also hierarchical. For details, refer to WMI in msdn. NET platform development, it is best to read more about.. NET introduces new features, which can greatly improve the Code development efficiency and running efficiency.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.