检索VBS中Active Directory用户或组的递归组成员身份

时间:2013-04-03 11:52:22

标签: vbscript active-directory

有很多关于如何使用memberOf属性的例子,但我找不到任何符合我需要的工作脚本。所以我写了自己的,我希望在这里分享我的脚本会有所帮助。

下面的脚本有2个工作示例。第一个示例Set GroupsOfUser = GetMembership(oAD.UserName, null)检索当前登录用户的成员身份。第二个示例Set GroupsOfGroup = GetMembership("CN=SomeGroup,OU=MyGroupContainer,DC=MyDomain,DC=local", null)演示了特定组的成员资格。

以下函数返回唯一值,并且不像大多数示例那样进入无限循环。

1 个答案:

答案 0 :(得分:0)

'Get the recursive groups from the active user
Set oAD = CreateObject("ADSystemInfo")
Set GroupsOfUser = GetMembership(oAD.UserName, null)
MsgBox Join(GroupsOfUser.Items(), "," & vbCrLf)

'Get the recursive groups from a specific group
Set GroupsOfGroup = GetMembership("CN=SomeGroup,OU=MyGroupContainer,DC=MyDomain,DC=local", null)
MsgBox Join(GroupsOfGroup.Items(), "," & vbCrLf)


Function GetMembership(sChild, dMembership)
  'Get AD info on the given Child
  Set oChild = GetObject("LDAP://" & sChild)

  If TypeName(oChild) = "Object" Then
    'Add the Child's canonical name to the array IF it's a group
    If TypeName(dMembership) = "Dictionary" Then
      dMembership.Add oChild.distinguishedName, oChild.CN
    Else
      Set dMembership = CreateObject("Scripting.Dictionary")
    End If

    'If the Child has any parents (=groups), run the same loop for these parents.
    If TypeName(oChild.memberOf) = "Variant()" Then
      oParents = oChild.GetEx("memberOf")
      For Each sParent in oParents
        If Not dMembership.Exists(sParent) Then
          Set dMembership = GetMembership(sParent, dMembership)
        End If
      Next
    End If
  End If

  Set GetMembership = dMembership
End Function