Finding AD User by SAMAccountName

by Aug 2, 2016

PowerShell 5

The free Microsoft RSAT tools come with a full-blown ActiveDirectory module, but sometimes simple AD tasks can be mastered with just a bit of .NET code, and no dependencies to the RSAT tools.

As an example, here is a function that can search users by SAMAccountName:

function Find-SamAccountName 
{
  param($SAMAccountName)

  $root = [ADSI]''
  $searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ($root)
  $searcher.filter = "(&(objectClass=User)(sAMAccountName=$SAMAccountName))"
  $searcher.findall() | ForEach-Object {
    $user = $_.GetDirectoryEntry()
  }
}

If you know ActiveDirectory a bit, you’ll quickly discover that at its heart, the function uses an LDAP search query, so you can easily use this as a template for all kinds of searches.

Twitter This Tip! ReTweet this Tip!