This post provides examples of how we can manipulate Active Directory user accounts using the ADSI Searcher instead of the ActiveDirectory PowerShell Module.

Most Google searches provide examples that use the PowerShell ActiveDirectory module cmdlets such as Get-ADUser and Get-ADComputer.  Whilst these work well, they require that Remote Server Administration Tools (RSAT) is installed locally. And sometimes this prerequisite is a pain in the backside if I’m working on a machine without it.

An alternative is to use the ADSI searcher.  In its most basic form, we can search a specific organisational unit (OU) like so:

$Root = [ADSI]"LDAP://OU=users,DC=alkanesolutions,DC=co,DC=uk"
$Searcher = new-object System.DirectoryServices.DirectorySearcher($Root)
$Searcher.filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PageSize = 200

$Searcher.FindAll() | % {
  
    $user = [adsi]$_.Properties.adspath[0]

    #print a list of Active Directory attributes that we can use
    write-host ($user.properties.PropertyNames)

    #as an example, we'll print the user's department
    $department = $user.properties.department
    write-host  $department 
   
}

It’s quite self explanatory.  Here we’re searching through all users in the following OU: OU=users,DC=alkanesolutions,DC=co,DC=uk

If we wanted to filter out disabled users, we could change the filter to this:

$Searcher.filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"

and if we wanted to search only for a specific user, we could change the filter to this:

$Searcher.filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=alkaneuser))"

We can also update user attributes like so:

$Root = [ADSI]"LDAP://OU=users,DC=alkanesolutions,DC=co,DC=uk"
$Searcher = new-object System.DirectoryServices.DirectorySearcher($Root)
$Searcher.filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PageSize = 200

$Searcher.FindAll() | % {
  
    $user = [adsi]$_.Properties.adspath[0]

    $user.Put("department", "IT Department"); 
    $user.setinfo();
   
}

If we don’t set the PageSize to something respectable, you’ll probably run into memory issues when performing updates on a large data set.  So I typically set it to 200 if I’m updating a large dataset of several thousand user records.

What you may (and probably should) also wish to do to speed things up, is only bring back the properties you require.  You can do this like so:

$propertiesRequired= "samaccountname", "mail", "extensionattribute11", "department", "distinguishedName", "l", "st", "displayName","lastLogonTimestamp"
foreach ($i in $propertiesRequired) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 

 

 

ADSI Searcher and the ActiveDirectory PowerShell Module
Comments have now been disabled. If you have a question to ask about this post please ask the community!