我正在使用sql server从Active Directory导入组和用户。我找到了以下代码来拉取组和用户。
CREATE TABLE ##Groups ( CN VARCHAR(128), DN VARCHAR(1024), Email VARCHAR(128), ADSPath VARCHAR(1024));
CREATE TABLE ##Users ( DistributionGroup VARCHAR(128), FirstName VARCHAR(50), LastName VARCHAR(50), EmailAddress VARCHAR(128));
DECLARE @sql VARCHAR(1024)
SET @sql = 'INSERT INTO ##Groups (CN, DN, Email, ADSPath) SELECT CN, distinguishedName DN, mail Email, ADSPath FROM OpenQuery(ADSI, ''<LDAP://controller.domain.com:389/DC=domain,DC=com>;(&(objectClass=Group));cn, distinguishedName, mail, ADSPath;subtree'') ORDER BY distinguishedName';
EXEC(@sql);
DECLARE @CN VARCHAR(128)
DECLARE @DN VARCHAR(1024)
SELECT TOP 1 @CN = CN, @DN = DN FROM ##Groups
WHILE EXISTS(SELECT DN FROM ##Groups WHERE DN > @DN)
BEGIN
SET @sql = 'INSERT INTO ##Users (DistributionGroup, Firstname, LastName, EmailAddress) SELECT '''+@CN+''' [Distribution Group], ISNULL(givenName, '''') FirstName, ISNULL(sn, '''') LastName, mail EmailAddress FROM OpenQuery(ADSI, ''<LDAP://controller.domain.com:389/DC=domain,DC=com>;(&(objectClass=User)(memberOf='+@DN+'));givenName, sn, mail;subtree'')';
EXEC(@sql)
SELECT TOP 1 @CN = CN, @DN = DN FROM ##Groups WHERE DN > @DN
END
SELECT * FROM ##Groups;
SELECT * FROM ##Users;
DROP TABLE ##Groups;
DROP TABLE ##Users;
这很好用。现在,我想拉出组的描述,但我似乎无法找出该字段的名称。帮助
答案 0 :(得分:7)
AD中的组说明存储在 description 属性中。
编辑:在SQL中使用ADSI链接服务器似乎无法实际提取描述属性,因为它是一个多值属性。有关从AD中提取数据以导入SQL Server的替代方法,请参阅my answer to this question。