Find Disabled Users in Active Directory using PowerShell

A PowerShell script to find disabled users in Active Directory:  The script uses the typical System.DirectoryServices.DirectorySearcher code to search AD. The key, as always is the search filter. In this case, we're searching for disabled users. Unfortunately, there is no attribute that holds the enabled/disabled status of the user. Suprising. It turns out that the disabled status is stored as a bit in the useraccountcontrol attribute. This attribute contains a number that is made up of binary bits, each having a different meaning. You can look up the meaning of each bit on MSDN at http://msdn.microsoft.com/en-us/library/ms680832(VS.85).aspx

Anyway, the second bit (2) is the account disabled bit.

Microsoft has given us a way to make a search filter that can search against a bit in an attribute, called LDAP matching rules. They are specified by OID's (long ugly numbers). According to the Search Filter Syntax page (http://msdn.microsoft.com/en-us/library/aa746475(VS.85).aspx), 1.2.840.113556.1.4.803 is equivelant to a bitwise AND.

So here's the script. The search filter does a bitwise AND of the contents of the useraccountcontrol attribute and the number 2 (remember the 2 bit means disabled). So the script searches for everyone in your AD that has the 2 bit set (disabled users).

$domain = New-Object System.DirectoryServices.DirectoryEntry
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot = $domain
$searcher.PageSize = 1000
$searcher.Filter = "(&(objectCategory=User)(userAccountControl:1.2.840.113556.1.4.803:=2))"
$proplist = ("cn","displayName")
foreach ($i in $propList){$prop=$searcher.PropertiesToLoad.Add($i)}
$results = $searcher.FindAll()
foreach ($result in $results){
 "$($result.properties.item("cn"))`t$($result.properties.item("displayName"))"
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...