I have two queries that retrieve all groups and all users in a domain, Mydomain
--; Get all groups in domain MyDomain
select *
from OpenQuery(ADSI, '
SELECT samaccountname,mail,sn,name, cn, objectCategory
FROM ''LDAP://Mydomain/CN=users,DC=Mydomain,DC=com''
WHERE objectCategory=''group''
ORDER BY cn
')
--; Get all users in domain MyDomain
select *
from OpenQuery(ADSI,'
SELECT objectCategory, cn, sn, mail, name, department,samaccountname
FROM ''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com''
WHERE objectCategory=''user''
ORDER BY cn
')
-- where samaccountname='mylogin'
What I would like to find out is,
How do you retrieve a list of all groups in MyDomain
that a particular user belongs to?
[UPDATE] I was able to get the opposite result
Given the group name, retrieve all users
select *
from OpenQuery(ADSI,
'SELECT objectCategory, cn, sn, mail, name, department
FROM ''LDAP://Mydomain/CN=users,DC=wl-domain,DC=com''
WHERE MemberOf=''cn=_____GROUPNAME_____,CN=users,DC=Mydomain,DC=com''
ORDER BY cn'
)
Stored procedure below, execute using example:
Get_ADGroups_ForUser 'Beau.Holland' --AccountName
Note: replace LDAP://DC=Domain,DC=local with your own domain.
CREATE PROCEDURE dbo.Get_ADGroups_ForUser
(
@Username NVARCHAR(256)
)
AS
BEGIN
DECLARE @Query NVARCHAR(1024), @Path NVARCHAR(1024)
-- Find the fully qualified CN e.g: CN=Beau Holland,OU=Users,OU=Australia,OU=NSO,OU=Company,DC=Domain,DC=local
-- replace "LDAP://DC=Domain,DC=local" with your own domain
SET @Query = '
SELECT @Path = distinguishedName
FROM OPENQUERY(ADSI, ''
SELECT distinguishedName
FROM ''''LDAP://DC=Domain,DC=local''''
WHERE
objectClass = ''''user'''' AND
sAMAccountName = ''''' + @Username + '''''
'')
'
EXEC SP_EXECUTESQL @Query, N'@Path NVARCHAR(1024) OUTPUT', @Path = @Path OUTPUT
-- get all groups for a user
-- replace "LDAP://DC=Domain,DC=local" with your own domain
SET @Query = '
SELECT cn,AdsPath
FROM OPENQUERY (ADSI, ''<LDAP://DC=Domain,DC=local>;(&(objectClass=group)(member:1.2.840.113556.1.4.1941:=' + @Path +'));cn, adspath;subtree'')'
EXEC SP_EXECUTESQL @Query
END
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With