Search code examples
windowspowershellgoregistry

Getting the NetCfgInstanceId of a NIC


If you know the name of a network card, how can you get its instance ID? eg: WLAN 2 {74892867-F98B-454B-904F-88912DDE4B9F}. I don't want to use the command line; it's better to work with the registry. What should be the policy that matches the network card in the registry (HKLM/SYSTEM/CurrentControlSet/Control/Class/{4d36e972-e325-11ce-bfc1-08002be10318})?

Language: Go 1.11
Platform: Windows 10


Solution

  • Get All NetCfgInstanceId on Your Windows.

    package main
    
    import (
        "fmt"
        "log"
    
        "golang.org/x/sys/windows/registry"
    )
    
    const ADAPTER_KEY = `SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}`
    
    func main() {
        k, err := registry.OpenKey(registry.LOCAL_MACHINE, ADAPTER_KEY, registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE)
        if err != nil {
            log.Fatal(err)
        }
        defer k.Close()
    
        keyNames, err := k.ReadSubKeyNames(-1)
        if err != nil {
            log.Fatal(err)
        }
    
        for _, keyName := range keyNames {
            n, _ := matchKey(k, keyName)
            if n != "" {
                fmt.Println(n)
            }
        }
    }
    
    func matchKey(zones registry.Key, keyName string) (string, error) {
        k, err := registry.OpenKey(zones, keyName, registry.READ)
        if err != nil {
            return "", err
        }
        defer k.Close()
    
        netCfgInstanceId, _, err := k.GetStringValue("NetCfgInstanceId")
        if err != nil {
            return "", err
        }
    
        return netCfgInstanceId, nil
    }