VBS- Login script to map drive with multiple NICs

320 views Asked by At

I am trying to create a script to map drive at logon as per IP address or subnet. I was able to find one script which works well on single MIC, but thre are few machines who have 2 Nics, and it does not work with them.

Here is modified script.

set objNetwork = CreateObject("Wscript.Network")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colAdapters = objWMIService.ExecQuery _
    ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled=True")


ReDim arrSubnets(-1)
For Each objAdapter in colAdapters
  For Each strAddress in objAdapter.IPAddress
    arrOctets = Split(strAddress, ".")
    If arrOctets(0) <> "" Then
      ReDim Preserve arrSubnets(UBound(arrSubnets)+1)
      arrSubnets(UBound(arrSubnets)) = arrOctets(0) & "." & arrOctets(1) & "." _
        & arrOctets(2)

    End If
  Next
Next

    Set colItems = objWMIService.ExecQuery _ 
        ("Select * From Win32_LogicalDisk Where DeviceID = 'G:'") 
If colItems.Count = 0 Then


    strSubnet = arrSubnets(UBound(arrSubnets))
 Select Case strSubnet


       Case "10.1.1" 
            objNetwork.MapNetworkDrive "G:", "\\10.1.1.62\zShared",True
        objNetwork.MapNetworkDrive "F:", "\\10.1.1.62\zShared2",True

        Case "10.1.20" 
            objNetwork.MapNetworkDrive "G:", "\\10.1.20.150\sharedch",True
        objNetwork.MapNetworkDrive "F:", "\\10.1.20.150\sharedch1",True 
End Select

End If
1

There are 1 answers

14
Ansgar Wiechers On

You use arrSubnets without initializing (or resizing) it. Also, you're trying to echo arrSubnetIPs(i) when you should be echoing arrSubnets(i). Change this:

i = 0

For Each objAdapter in colAdapters
  For Each strAddress in objAdapter.IPAddress
    arrOctets = Split(strAddress, ".")
    If arrOctets(0) <> "" Then
      arrSubnets(i) = arrOctets(0) & "." & arrOctets(1) & "." & arrOctets(2)
      i = i + 1
      WScript.Echo arrSubnetIPs(i)
    End If
  Next
Next

into this:

ReDim arrSubnets(-1)
For Each objAdapter in colAdapters
  For Each strAddress in objAdapter.IPAddress
    arrOctets = Split(strAddress, ".")
    If arrOctets(0) <> "" Then
      ReDim Preserve arrSubnets(UBound(arrSubnets)+1)
      arrSubnets(UBound(arrSubnets)) = arrOctets(0) & "." & arrOctets(1) & "." _
        & arrOctets(2)
      WScript.Echo arrSubnets(UBound(arrSubnets))
    End If
  Next
Next