powershell and active directory searching

I’ve been doing some more work using PowerShell for small ad-hoc types of scripts. Basically I keep some notes around, and adjust those notes for what I need at the time. This works great when I need to query certain things from our Active Directory. While we use AD a lot, only my team uses it, which means it gets messy and out of sync quickly.

A recent request needed me to pull all the supervisors and managers in our company. Odd, but no one keeps a list of these, nor do we have neat groups in AD to accomodate the request. Great. I could, however, pull out everyone who is listed as having a “direct report” in their AD account, which is something the desktop techs *are* good about updating.*

$objADSearcher = new-object DirectoryServices.DirectorySearcher([ADSI]””)
$objADSearcher.filter = “(&(ObjectClass=User))”
$objFoundUsers = $objADSearcher.FindAll()

[array]$objADUsers = @()

foreach ($t in $objFoundUsers)
   if ($t.properties.directreports)
      $objADUsers += $t

This snippet will search out all user accounts in AD and display the names of those who have direct reports. Further properties on any given account can be found by doing a .properties to it, .e.g $objADUsers[45].properties.
I’ve also had a need to quickly find all the members of a group in a way that allows me to copy and paste the results.

$i = “Supervisors Group”
$objADSearcher = new-object DirectoryServices.DirectorySearcher([ADSI]””)
$objADSearcher.filter = “(&(ObjectClass=Group)(name=$i))”
$objFoundGroup = $objADSearcher.FindAll()

This will display the result of the search for Supervisors Group. If only one object is returned, I often forget that I still need to reference it by index[0].

Now, if I get a user back and want to connect directly into their AD object, I need to leverage the path property.

$ADSPath = $objFoundUsers.path
$container = [ADSI]$ADSPath

* I am positive there are many ways to accomplish these tasks, and I may not be doing the most optimal method, however, this method does work for me for now, until I find some better way.