T-SQL To Query Inactive Accounts in AD

I needed a query to pull current Active Directory (AD) accounts and determine which accounts should be inactive.  The main limitation is Active Directory’s 1000 object return with queries.    I structured the organizational units (OU) so that different sites are in different OU’s.  Structuring the data in AD this way makes it so that pulling data will be less than the 1000 object limitation for queries.  I don’t want orphaned accounts in Active Directory to remain active accounts.  So pulling from AD and comparing those users with users in the database help me to determine the orphaned users or users that should be inactived.

SELECT TOP 100 sAMAccountName AS Username
	(SELECT TOP 1000 sAMAccountName
	FROM OpenQuery  
		 ) AS AD
	WHERE sAMAccountName NOT IN (
			SELECT DISTINCT ActiveUsers.Username
			FROM     dbo.ActiveUsers
			WHERE      ActiveUers.Active = 1





Leave a Reply

%d bloggers like this: