Wrappers Revisited

Yesterday I talked about some “wrapper” functions I use to make the .Net 2.0 AD DirectorySearcher and DirectoryEntry classes easier to use. Then I learned from Marc van Orsouw (better known as  /\/\o\/\/) that I was being too verbose in my use of DirectorySearcher. With Marc’s tips, I could simplify my get-ADEntry function and eliminate the get-UserDN function. (By the way, if you haven’t visited Marc’s site recently, you’re missing some really good Powershell and AD info.)

Instead of

$SearchResults = $Searcher.FindOne()
New-Object DirectoryServices.DirectoryEntry (“LDAP://” + ($SearchResults.properties.distinguishedname))

I could just use

$Searcher.FindOne().GetDirectoryEntry()

So now my get-ADEntry function looks like this

function get-ADEntry {
  param ($LdapPath=””, $samAccount=””, $Guid=””, $SmtpAddress=””)
  $Searcher = New-Object DirectoryServices.DirectorySearcher

  if ($LdapPath -ne “”) {
    New-Object DirectoryServices.DirectoryEntry (“LDAP://” + $LdapPath)
  }
  elseif ($samAccount -ne “”) {
    $Searcher.Filter = “(&(objectCategory=person)(objectClass=user)(samAccountName=$samAccount))”
    $Searcher.FindOne().GetDirectoryEntry()
  }
  elseif ($SmtpAddress -ne “”) {
    $Searcher.Filter = “(&(objectCategory=person)(objectClass=user)(proxyaddresses=smtp:$SmtpAddress))”
    $Searcher.FindOne().GetDirectoryEntry()
  }
  elseif ($Guid -ne “”) {
    New-Object DirectoryServices.DirectoryEntry (“LDAP://<GUID=” + (get-NativeGuid $Guid) + “>”)
  }
  else {
    New-Object DirectoryServices.DirectoryEntry
  }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s