Home > Backend Development > Golang > How Can I Easily Query WMI from Go?

How Can I Easily Query WMI from Go?

Mary-Kate Olsen
Release: 2024-11-28 18:38:11
Original
278 people have browsed it

How Can I Easily Query WMI from Go?

Querying WMI from Go

To execute WMI queries from Go, utilizing DLL calls is feasible. However, navigating the complexities of COM-based Windows APIs can be daunting. Fortunately, there are alternative solutions that provide a more straightforward approach.

One recommended solution is to leverage the GitHub repository by StackExchange/wmi. This package encapsulates the techniques outlined in the accepted answer, offering a convenient interface for WMI queries.

Using the StackExchange/wmi Package

Here's a code snippet that demonstrates how to use the StackExchange/wmi package:

package main

import (
        "context"
        "fmt"
        "log"

        "github.com/StackExchange/wmi"
)

func main() {
        query := wmi.CreateQuery(&wmi.Query{
                Namespace:  "root\cimv2",
                Query:      "SELECT * FROM Win32_Process",
                Projection: []string{"Caption", "ProcessId"},
        })
        processes, err := query.Execute(context.Background())
        if err != nil {
                log.Fatal(err)
        }
        fmt.Printf("%-5s%-20v", "PID", "Name")
        fmt.Println()
        for _, p := range processes {
                fmt.Printf("%-5v%-20v\n", p.Properties["ProcessId"].Value.Value().(uint32), p.Properties["Caption"].Value.Value().(string))
        }
}
Copy after login

This example will fetch information about running processes, including their process IDs and names. The StackExchange/wmi package handles the intricacies of COM and WMI, simplifying the querying process for Go developers.

The above is the detailed content of How Can I Easily Query WMI from Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template