Qazxswe
Qazxswe

Reputation: 149

Script is obtaining wrong NIC IP details

I am using the below script to obtain the IP address of the target machine and then map a drive to another PC on the same network by adjusting the last octet.

This works well but I now have to run this on machines with two NICs (named Primary and Internal) and the script picks up the IP of the wrong NIC (Internal)

How can I get it to look at the IP of the other NIC?

Dim HostIPAddress : HostIPAddress = ""
Dim objWMIService : Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Dim colAdapters : Set colAdapters = objWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
Dim objAdapter
For Each objAdapter In colAdapters
  If Not IsNull(objAdapter.IPAddress) Then HostIPAddress = Trim(objAdapter.IPAddress(0))
  Exit For
Next

strIP = HostIPAddress
i = InStrRev(strIP, ".")
strIP = Left(strIP, i) & "15"

Dim objNetwork 
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile

strDriveLetter = "Z:" 
strRemotePath = "\\"&strIP&"\c$" 
strUser = "User"
strPassword = "Password!"
strProfile = "false"

Set objNetwork = WScript.CreateObject("WScript.Network") 
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
  strProfile, strUser, strPassword

Upvotes: 0

Views: 250

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200463

Get the device ID of the NIC that is named "primary" via the Win32_NetworkAdapter class, then use that ID for selecting the correct adapter from the Win32_NetworkAdatperConfiguration class.

nicName = "primary"

Set wmi = GetObject("winmgmts://./root/cimv2")

deviceQry = "SELECT * FROM Win32_NetworkAdapter " & _
            "WHERE NetConnectionId = '" & nicName & "'"
For Each adapter In wmi.ExecQuery(deviceQry)
  addressQry = "SELECT * FROM Win32_NetworkAdapterConfiguration " & _
               "WHERE Index = " & adapter.DeviceId
  For Each config In wmi.ExecQuery(addressQry)
    If Not IsNull(config.IPAddress) Then
      HostIPAddress = Trim(config.IPAddress(0))
      Exit For
    End If
  Next
Next

Upvotes: 1

Related Questions