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.DirectorySearcherif ($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
}
}