We recently helped out with a data migration which included creating a completely new set of Active Directory security groups. They wanted all the members to have the same level of access but wanted all the new security groups to have a matching standard.
So we needed to create all the new security groups and then add all the existing members into the new ones that we had created. Considering that some of the existing security groups had 100’s of members, we needed to find a quick and simple way to copy and paste the members into the new security groups.
We found a SQL query on the internet here that worked perfectly for us, also gave us a lot of other information that we can use for future queries.
SQL query to find members of an AD security group
DECLARE @group NVARCHAR(128) = 'AD GroupName' DECLARE @DC1 NVARCHAR(128) = 'domain' DECLARE @DC2 NVARCHAR(128) = 'com' DECLARE @SQL NVARCHAR(MAX) DECLARE @group_dn NVARCHAR(512) DECLARE @result TABLE(name NVARCHAR(512)) SET @SQL = 'SELECT distinguishedName FROM OPENQUERY (ADSI,''SELECT cn, distinguishedName, dc FROM ''''LDAP://DC=' + @DC1 + ',DC=' + @DC2 + ''''' WHERE objectCategory = ''''group'''' AND cn = ''''' + @group + ''''''')' --PRINT @SQL INSERT @result(name) EXEC sp_executesql @SQL SELECT @group_dn = name FROM @result SET @SQL = 'SELECT * FROM OPENQUERY (ADSI, ''<LDAP://' + @DC1 + '.' + @DC2 + '>; (&(objectCategory=person)(memberOf:1.2.840.1135126.96.36.1991:=' + @group_dn + ')); cn, sAMAccountName, givenName, sn, mail;subtree'') ORDER BY cn;' --PRINT @SQL EXEC sp_executesql @SQL
Remember to state your declare variables at the top of query.
Thanks to the original poster as we were able to then simply copy and paste the column one that is produced and paste that into our new security group!
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?