Thursday, December 21, 2006

Get the users' memberOf from Active Directory

Sometime you need to do an audit of your Enterprise users and make sure they are a member of the proper security group and distribution list within your Active Directory.

Here is the code in VBScript and talking to AD with LDAP:

On Error Resume Next
Dim OutPutFileDim FileSystem

Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set OutPutFile = FileSystem.CreateTextFile("users.txt", True)

'-- Number value of the error return by ADSI if the '-- memberOf attribute cannot be found.
'==================================================
Const E_ADS_PROPERTY_NOT_FOUND = &h8000500D

'-- Bind to the Users container'==============================
Set objOU = GetObject("LDAP://OU=Users,dc=domain,dc=com")

'-- Initialize the array for user accounts.
'==========================================
ObjOU.Filter= Array("user")

'-- Control Loop
'===============
For Each objUser in objOU
OutPutFile.WriteLine objUser.cn & " is a member of: "

'-- Use the GetEX method to intialize the array for group
'-- membership. Get method cannot be used as it does not
'-- multivalued attributes (user can be member of many groups.)
'============================================================== arrMemberOf = objUser.GetEx("memberOf")

'-- If the error is not raised from ADSI, then list the
'-- groups that are entries within the arrMemberOf array.
'-- If error is raised, display notification on screen.
'========================================================
If Err.Number <> E_ADS_PROPERTY_NOT_FOUND Then
For Each Group in arrMemberOf
OutPutFile.WriteLine vbTab & Group
Next
Else
Err.Clear
End If
Next

'Clean up
OutPutFile.CloseSet
FileSystem = Nothing

No comments: