如何检索 LAN 适配器 MAC 地址?

How can I retrieve the LAN adapter MAC address?

我想从 Windows 系统中检索 MAC 地址,仅用于 LAN 适配器。你能建议我如何在 VBScript 中处理这个问题吗?

我目前正在使用此 VBScript 获取 MAC 地址,但这会为我提供所有适配器的结果,而当我连接到 LAN 适配器时我只需要 MAC 地址.

strComputer = "."
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration") 
For Each objItem in colItems
  If objItem.ServiceName <> "VMnetAdapter" AND isNull(objItem.MACAddress)=0 Then  
    Wscript.Echo objItem.MACAddress
    Wscript.Echo objItem.ServiceName
  End if
Next

这个怎么样

方式一:

如果可能,尝试排除所有不需要的适配器(排除 VmWare 和 VirtualBox)。当然,在某些计算机上可能会有更具体的适配器,您需要找出并排除这些适配器

strComputer = "."  
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")  
Set colItems = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration")  
For Each objItem in colItems  
    if objItem.ServiceName <> "VMnetAdapter" and objItem.ServiceName <> "VBoxNetAdp" and objItem.ServiceName <> "" and isNull(objItem.MACAddress) = 0 Then  
            Wscript.Echo objItem.ServiceName & vbCrLf & objItem.MACAddress
    End if    
Next

方式 2:

查找具有特定网关的所有适配器

strComputer = "."  
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")  
Set colItems = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration")  
For Each objItem in colItems  
    if objItem.ServiceName <> "VMnetAdapter" and objItem.ServiceName <> "VBoxNetAdp" and objItem.ServiceName <> "" and isNull(objItem.MACAddress) = 0 Then  
        For Each strIP in objItem.DefaultIPGateway
            If strIP = "192.168.1.1" Then
                    Wscript.Echo objItem.ServiceName & vbCrLf & objItem.MACAddress
            End If
        Next
    End if    
Next

https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx

使用 Win32_NetworkAdapter class 而不是 Win32_NetworkAdapterConfiguration class。后者没有 属性 提供适配器名称。

adaptername = "LAN Adapter"

Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & adaptername & "'" 
For Each adapter In wmi.ExecQuery(qry)
  If Not IsNull(adapter.MACAddress) Then Wscript.Echo adapter.MACAddress
Next

试试这个,你会得到 MAC 只有 LAN 适配器的地址,

Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionID like '%Local Area Connection%')"
For Each adapter In wmi.ExecQuery(qry)
  If Not IsNull(adapter.MACAddress) Then Wscript.Echo adapter.MACAddress
Next

我只使用这段代码并且它工作正常。