Querying WMI from Go: Using COM Objects
WMI (Windows Management Instrumentation) provides a standardized interface for accessing management and configuration information on Windows systems. In Go, it's possible to query WMI using the COM (Component Object Model) framework.
Using the "github.com/StackExchange/wmi" Package
The recommended approach is to utilize the "github.com/StackExchange/wmi" package, which provides a stable and comprehensive wrapper for WMI operations in Go. This package leverages the solution discussed in the accepted answer, simplifying the process of initializing COM and executing WMI queries.
Composing a WMI Query
To compose a WMI query, use the "ExecQuery" function provided by the package. For example:
import "github.com/StackExchange/wmi" func main() { query := wmi.CreateQuery(&wmi.Query{ Namespace: `root\cimv2`, Query: `SELECT * FROM Win32_Process`, })
Executing the Query
Once the query is composed, execute it using the "Find" function:
results, err := query.Find() if err != nil { // Handle error }
Retrieving Results
The "Find" function returns a slice of "wmi.Record" objects, each representing a matching instance from the WMI namespace. To access the properties of a record:
for _, record := range results { name, err := record.Property("Name") if err != nil { // Handle error } fmt.Println(name.Value) }
Example Code
Here is a complete example program demonstrating how to query WMI for process names:
package main import ( "fmt" "github.com/StackExchange/wmi" ) func main() { query := wmi.CreateQuery(&wmi.Query{ Namespace: `root\cimv2`, Query: `SELECT Name FROM Win32_Process`, }) results, err := query.Find() if err != nil { // Handle error } for _, record := range results { name, err := record.Property("Name") if err != nil { // Handle error } fmt.Println(name.Value) } }
The above is the detailed content of How to Query Windows Management Instrumentation (WMI) from Go using COM Objects?. For more information, please follow other related articles on the PHP Chinese website!