Share

Several of the logon scripts I develop for clients perform things like drive-mapping based whether or not the user or computer are a member of a particular security group.  As such, I needed a function to check group membership.  I found several different examples and ultimately settled on my own implementation after some trial and error.  The following is the actual VBScript function I use on our logon scripts [we attach them to a group policy object (GPO)]:

'********************************************************************
'*
'* Function IsGroupMember()
'* Purpose : Determines if the specified object is a member of the
'*               specified group.
'* Input ..: UserOrComputerDN - [String] The distinguished name of
'*                               the user or computer to check.
'*           GroupName        - [String] The name of the group to
'*                               check membership of.
'* Output .: True  - The user is a member.
'*           False - The user is not a member, the group does not
'*                   exist, or the user does not exist.
'*
'********************************************************************
Function IsGroupMember(ByVal UserOrComputerDN, ByVal GroupName)
	On Error Resume Next
	Dim iRet
	Dim objUserOrComputer
	Dim objGroup
	Dim sGroup
	Dim colGroups
	iRet = False
 
	'Bind user or computer AD object.
	Set objUserOrComputer = GetObject("LDAP://" & UserOrComputerDN)
	If ((Err.Number = 0) And (IsObject(objUserOrComputer))) Then
		'Get the collection of groups the object is a member of.
		colGroups = objUserOrComputer.MemberOf
		If (Not IsEmpty(colGroups)) Then
			If (TypeName(colGroups) = "String") Then
				'User is a member of only one group.
				Set objGroup = GetObject("LDAP://" & colGroups)
				If ((Err.Number = 0) And (IsObject(objGroup))) Then
					If (LCase(objGroup.CN) = LCase(GroupName)) Then
						iRet = True
					End If
				End If
			Else
				'Object is a member of multiple groups.
				'Iterate through the groups the user is a member of and see
				'if any of them match the specified group.
				For Each sGroup In colGroups
					Set objGroup = GetObject("LDAP://" & sGroup)
					If ((Err.Number = 0) And (IsObject(objGroup))) Then
						If (LCase(objGroup.CN) = LCase(GroupName)) Then
							iRet = True
							Exit For
						End If
					End If
				Next
			End If
		End If
	End If
 
	'Dispose objects and return.
	Set objGroup = Nothing
	Set objUserOrComputer = Nothing
	IsGroupMember = iRet
End Function

So you could use the above function like this:

Dim userDN
Dim securityGroup
securityGroup = "sStaff"
userDN = "CN=John Doe,OU=My Division,DC=fabrikam,DC=com"
If IsGroupMember(userDN, securityGroup) Then
   MsgBox "User is a member of " & securityGroup
Else
   MsgBox "User is not a member"
End If