Home >Backend Development >Golang >How Can I Query Windows Management Instrumentation (WMI) from Go Using COM?

How Can I Query Windows Management Instrumentation (WMI) from Go Using COM?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 02:31:14898browse

How Can I Query Windows Management Instrumentation (WMI) from Go Using COM?

Querying WMI from Go Using COM

In the realm of Windows administration, querying Windows Management Instrumentation (WMI) is a crucial task. For those seeking a way to accomplish this from within Go, the following solution provides a straightforward approach utilizing COM.

Mattn, a contributor on GitHub, has created a convenient wrapper that simplifies the process. Employing this wrapper along with necessary error handling, here's an example program:

import (
    "github.com/mattn/go-ole"
    "github.com/mattn/go-ole/oleutil"
)

func main() {
    // Initialize and later uninitialize COM
    ole.CoInitialize(0)
    defer ole.CoUninitialize()

    // Create WbemScripting.SWbemLocator object
    unknown, _ := oleutil.CreateObject("WbemScripting.SWbemLocator")
    defer unknown.Release()

    // Obtain SWbemServices object
    wmi, _ := unknown.QueryInterface(ole.IID_IDispatch)
    defer wmi.Release()
    serviceRaw, _ := oleutil.CallMethod(wmi, "ConnectServer")
    service := serviceRaw.ToIDispatch()
    defer service.Release()

    // Execute WMI query
    resultRaw, _ := oleutil.CallMethod(service, "ExecQuery", "SELECT * FROM Win32_Process")
    result := resultRaw.ToIDispatch()
    defer result.Release()

    // Gather process names
    countVar, _ := oleutil.GetProperty(result, "Count")
    count := int(countVar.Val)
    for i := 0; i < count; i++ {
        itemRaw, _ := oleutil.CallMethod(result, "ItemIndex", i)
        item := itemRaw.ToIDispatch()
        defer item.Release()
        asString, _ := oleutil.GetProperty(item, "Name")
        println(asString.ToString())
    }
}

In this code, the critical operation is the call to ExecQuery, which retrieves the desired WMI data. As an example, we retrieve the names of running processes. Running this program should produce a list of active processes on your system.

This solution leverages the power of COM, a legacy technology from the early days of object-oriented programming in C. While it may not be the most modern approach, it provides a stable and reliable way to interact with WMI from Go.

The above is the detailed content of How Can I Query Windows Management Instrumentation (WMI) from Go Using COM?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn