简体   繁体   中英

Active Directory - Get users and groups, member of a particular group

Primarily, I needed to retrieve a list of users who are members of a particular group, in SQL Server. I did managed to find something on the net, which is working perfectly. Solution is as shown:

CREATE PROCEDURE [dbo].[NES_GetADGroupMembers]
    (@groupName VARCHAR(max))
AS 
BEGIN
    CREATE TABLE #MemberOfGroups
    (
         groupName varchar(400),
         cn varchar(400),
         displayName varchar(400)
    )

    SET NOCOUNT ON

    DECLARE @t varchar(100), @t2 varchar(1000), 
            @ot varchar (4000), @tt varchar (4000);

    DECLARE gC CURSOR FOR
        SELECT cn, distinguishedName
        FROM openquery (ADSI, 'SELECT cn, distinguishedName
                               FROM ''''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com''''
                               WHERE objectCategory = ''group''')

    OPEN gC

    FETCH NEXT FROM gC INTO @t, @t2

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @ot = '''SELECT cn, displayName
                   FROM ''''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com'''' 
                   WHERE objectCategory = ''''Person'''' AND objectClass = ''''user''''
                     AND memberOf=''''' + @t2 + '''''';

       SET @tt = 'select '+ ''''+@t+'''' +' As groupName, cn, displayName from openquery(ADSI,'+ @ot +''') order by cn'

       INSERT INTO #MemberOfGroups (groupName, cn, displayName)
           EXEC (@tt) 

       FETCH NEXT FROM gC INTO @t, @t2
    END

    CLOSE gC
    DEALLOCATE gC

    SELECT 
        groupName, displayName 
    FROM
        #MemberOfGroups

For now, its just working fine, returning the users of the entered group.

However, I have a new request, whereby a group can have other 'groups' as member, just like the users.

I tried updating my filter in the WHERE condition to include objectClass = ''group'' , but it's not working.

Anyone knows a bit about these queries and can help me retrieve the groups (members of the input group) also?

I assume that your groups are inside of the OU (folder) of users? My AD setup has groups in a separate CN called SecurityGroups. Technically you could do:

SELECT cn, member FROM ''''LDAP://Mydomaindomain/CN=<actual OU of groups?>,DC=Mydomain,DC=com''''

as member will give you the DN of all of the members of that group. Then you have the array of members and just have to match those to their corresponding user (or group!) objects. Because this returns essentially an associative array of DNs, you can filter for the group objects and nest a query to run that again for the members of those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM