Map Windows drives based on group membership


Need a way to map a network share for a user, based on security group membership? It’s pretty easy and can be done with just a few lines of code. Using a Visual Basic Script, you can map a drive to a Windows share based on whether or not the authenticating Active Directory user is a member of a specific security group.

In this example, I have an Active Directory group named acct and I want the members of that group to have the share located at \\server01\acct mapped using the drive letter Q. The text in yellow, represents where you modify this script to accommodate your environment.

‘Set the variable ACCT to the group name acct
Const ACCT = "cn=acct"

‘Access to network resources.
Set wshNetwork = CreateObject("WScript.Network")

‘Network drive mapping info.
Set EnuDrives = wshNetwork.EnumNetworkDrives()

‘For checking group memberships
Set ADSysInfo = CreateObject("ADSystemInfo")
Set CurrentUser = GetObject("LDAP://" & ADSysInfo.UserName)

‘Prevents an error if user is not a member of any groups.
If IsArray(CurrentUser.MemberOf) Then
  strGroups = LCase(Join(CurrentUser.MemberOf))
Else
  strGroups = LCase(CurrentUser.MemberOf)
End If

‘This block first checks if the user is a member of
‘the ACCT group. If yes, then it checks for an existing
‘map using Q, if it finds one, it is disconnected and Q is
‘mapped to the \\server01\acct share.
If InStr(strGroups, ACCT) Then
  For i = 0 To EnuDrives.Count - 1 Step 2
    If LCase(EnuDrives.Item(i)) = "q:" Then
      wshNetwork.RemoveNetworkDrive "q:", True, True
    End If
  Next
  wshNetwork.MapNetworkDrive "q:", "\\server01\acct"
End If

Now just copy the above script and paste it into a text editor such as Notepad and name it with an .vbs extension. Double clicking the the file runs the script and you should see the Q: drive mapped to your specified share as long as you are a member of your specified group.

Leave a Reply