Search code examples
cmdvbscriptipconfig

Why isn't VBS properly running ipconfig /all?


I have come to you today with a problematic snippet of code I have.

Set mac = CreateObject("WScript.Shell").Exec("cmd.exe /C ipconfig /all")
Do While mac.Status = 0
  WScript.Sleep 100
Loop 
MsgBox "Your MAC address is " & vbNewLine & Left(Right(mac.StdOut.ReadAll, 775),756), vbExclamation, "Physical Address"
Set mac = Nothing

My goal is to find the physical address of the computer and return it with a msgbox;
However, upon running this program I am met with 2 things:

  1. The CMD program didn't close, even when I added a /C to the command.
  2. Upon closer inspection, I found (with the Len() function) that in CMD ipconfig /all counted over 6000 characters, but with this program, it stated that the command returned only 4000 characters.

I know for a fact that there is something wrong with Set mac = CreateObject("WScript.Shell").Exec("cmd.exe /C ipconfig /all") but I don't know even after checking other answers and such.


Solution

  • I would suggest, that you forget about running ipconfig.exe and then trying to parse all of its returned text to retrieve the MACAddress, and instead use WMI

    Example:

    Set WMI = GetObject("winmgmts:\\.\root\cimv2")
    Set NIC = WMI.ExecQuery("Select MACAddress " & _
      "From Win32_NetworkAdapter " & _
      "Where MACAddress Is Not NULL " & _
      "And NetEnabled='TRUE' " & _
      "And PhysicalAdapter='TRUE'") 
    For Each Adapter In NIC
      MsgBox "Your MAC Address is:" & vbNewLine & _
      Adapter.MACAddress, vbInformation, "Physical Address"   
    Next