Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for Disabled Active Directory Accounts

I need to query AD to determine if a users account is disabled.

Using a similar query used in the answers here

SELECT *
FROM OPENQUERY(ADSI, 'SELECT sAMAccountName
FROM ''LDAP://DC=MyDC,DC=com,DC=uk''
WHERE objectCategory = ''Person''
AND objectClass = ''user'')

I believe to determine if an account is disabled I have to use the userAccountControl field somehow. I've tried several things but they don't seem to be working:

WHERE userAccountControl & 2 <> 0
like image 925
Chris Klepeis Avatar asked Aug 24 '09 19:08

Chris Klepeis


People also ask

Can you query Active Directory from SQL?

The first method to query Active Directory from SQL Server is by using OpenRowSet. If you want to know more about openrowset please read this article. You can access information from Active directory by executing the following query.

How do I export disabled users from Active Directory?

Export disabled users from OUGet all disabled users from specific OU in Active Directory and export to CSV file. You need to copy the OU distinguishedName. Paste the OU distinguishedName in the below $OU variable.


2 Answers

Inside OPENQUERY() :

AND ''userAccountControl:1.2.840.113556.1.4.803:''<>2

SELECT *
FROM OPENQUERY(ADSI, 'SELECT sAMAccountName
FROM ''LDAP://DC=MyDC,DC=com,DC=uk''
WHERE objectCategory = ''Person''
AND objectClass = ''user''
AND ''userAccountControl:1.2.840.113556.1.4.803:''<>2)
like image 195
youhieng Avatar answered Oct 06 '22 00:10

youhieng


How about:

SELECT sAMAccountName
FROM OPENQUERY(ADSI, 'SELECT sAMAccountName, userAccountControl 
FROM ''LDAP://DC=MyDC,DC=com,DC=uk'' 
WHERE objectCategory = ''Person'' 
AND objectClass = ''user''') 
WHERE userAccountControl & 2 <> 0; -- disabled
like image 44
brejk Avatar answered Oct 06 '22 01:10

brejk