Wednesday, April 13, 2011

How to query active directory from SQL Server

There are two ways to query Active Directory from SQL Server. The easiest way for me is using OPENROWSET as explained below:

1) you need to run the following SQL sentences just one time

USE [master]
GO
sp_configure 'show advanced options',1
GO
reconfigure with override
GO
sp_configure 'Ad Hoc Distributed Queries',1
GO
reconfigure with override
GO

2) After running the senteces above, execute a query like the one below:

SELECT  * from OPENROWSET
('AdsDsoObject' ,
'User ID=domain\user;Password=myuserpassword;ADSI Flag=0x11;Page Size=10000',
'SELECT sn,givenName,mail FROM ''LDAP://OU=myOU,DC=myDomain,DC=com'' where ObjectClass=''User'''



)
wheremail is not null and
givenname is not null and
sn is not null and
order by mail

Take into account that:
  • domain\user is an account that can read the Active Directory and mypassword is the password for that account
  • ADSI Flag=0x11 is some type of authentication flag for ADSI (I really don´t know what flag can be)
  • The second SELECT sentence is the one you use to specify what domain and OU is you quering from. Inside this SELECT you can specify the type of object you need, for example, an User or a Computer. The objectclass="User" part of the inner select do that trick.
  • In all the sentence we never use quotation marks (") to enclose the text. The simbols are more like apostrophes.
  • You can include a WHERE clause at the end of the outer select but only to filter the results provided by the inner one
  • You can find a list of LDAP atributes in the following link: http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm

No comments:

Post a Comment